{"version":3,"file":"dist-DXQ9dYvL.mjs","names":["marker","symbol","_a","_b","name","marker2","symbol2","_a2","_b2","name2","marker3","symbol3","_a3","_b3","name3","marker4","symbol4","_a4","_b4","InvalidArgumentError","name4","marker5","symbol5","_a5","_b5","name5","marker6","symbol6","_a6","_b6","name6","marker7","symbol7","_a7","_b7","name7","marker8","symbol8","_a8","_b8","name8","marker9","symbol9","_a9","_b9","name9","marker10","symbol10","_a10","_b10","name10","marker11","symbol11","_a11","name11","marker12","symbol12","_a12","name12","marker13","symbol13","_a13","name13","marker14","symbol14","_a14","name14","marker15","symbol15","_a15","atob","btoa","name","marker","symbol","_a","_b","InvalidArgumentError","VERSION","APICallError2","ZodFirstPartyTypeKind2","ZodFirstPartyTypeKind3","zodSchema","TypeValidationError2","TypeValidationError3","APICallError3","resolve","textDecoder","APICallError4","fromSymbol","import_os","fs","path","symbol","_a","_b","name","marker2","symbol2","_a2","_b2","name2","marker3","symbol3","_a3","name3","marker4","symbol4","_a4","name4","marker5","symbol5","zodSchema","z","_a5","name5","marker6","symbol6","_a6","name6","marker7","symbol7","_a7","name7","marker8","symbol8","_a8","name8","marker9","symbol9","_a9","lazySchema2","zodSchema2","z2","name9","marker10","symbol10","_a10","safeValidateTypes2","lazySchema3","zodSchema3","z3","resolve","z4","lazySchema4","zodSchema4","getFromApi2","resolve2","createJsonResponseHandler2","createJsonErrorResponseHandler2","z5","lazySchema5","zodSchema5","getFromApi3","resolve3","createJsonResponseHandler3","createJsonErrorResponseHandler3","z6","lazySchema6","zodSchema6","resolve4","createJsonResponseHandler4","z7","createJsonErrorResponseHandler4","WORKFLOW_SERIALIZE2","serializeModelOptions2","WORKFLOW_DESERIALIZE2","resolve5","postJsonToApi2","combineHeaders2","createJsonResponseHandler5","createJsonErrorResponseHandler5","z8","lazySchema7","zodSchema7","WORKFLOW_SERIALIZE3","serializeModelOptions3","WORKFLOW_DESERIALIZE3","resolve6","postJsonToApi3","combineHeaders3","createJsonResponseHandler6","createJsonErrorResponseHandler6","z9","resolve7","postJsonToApi4","combineHeaders4","APICallError2","createJsonErrorResponseHandler7","z10","convertUint8ArrayToBase642","resolve8","postJsonToApi5","combineHeaders5","createJsonResponseHandler7","createJsonErrorResponseHandler8","z11","lazySchema8","zodSchema8","resolve9","postJsonToApi6","combineHeaders6","createJsonResponseHandler8","createJsonErrorResponseHandler9","z12","resolve10","postJsonToApi7","combineHeaders7","convertUint8ArrayToBase643","createJsonResponseHandler9","createJsonErrorResponseHandler10","z13","lazySchema9","zodSchema9","z14","createProviderExecutedToolFactory2","lazySchema10","zodSchema10","z15","createProviderExecutedToolFactory3","lazySchema11","zodSchema11","z16","VERSION","z17","postJsonToApi8","createJsonResponseHandler10","createJsonErrorResponseHandler11","ForeignKeyBuilder","ForeignKey","uniqueKeyName","ForeignKeyBuilder","uniqueKeyName","customType","integer","json","numeric","real","text","InlineForeignKeys","IndexBuilderOn","IndexBuilder","Index","index","uniqueIndex","primaryKey","PrimaryKeyBuilder","PrimaryKey","text","serializeSpanError","handle","getDatabaseHandle","getDbFromContext","require","buildPgSchema","buildSqliteSchema","text","integer","uniqueIndex","integer$1","uniqueIndex$1","index","index$1","tableRegistry","schema","getDb","eq$1","scopedAnd","and$1","max$1","ALGORITHM","IV_LENGTH","resolveEncryptionKey","marker","symbol","_a","marker2","symbol2","_a2","AISDKError3","AISDKError4","AISDKError5","AISDKError6","AISDKError7","AISDKError9","AISDKError10","AISDKError14","AISDKError15","getErrorMessage2","AISDKError16","AISDKError17","AISDKError18","AISDKError19","AISDKError20","AISDKError21","VERSION","DownloadError2","_exhaustiveCheck","getErrorMessage3","exhaustiveCheck","z","z2","z3","isBuffer2","z4","InvalidPromptError2","asArray2","z5","AISDKError23","asArray3","APICallError2","getErrorMessage4","asSchema2","resolve","safeParseJSON2","safeValidateTypes2","TypeValidationError2","asSchema3","safeParseJSON3","safeValidateTypes3","asArray4","convertUint8ArrayToBase642","convertBase64ToUint8Array2","isExecutableTool2","safeValidateTypes4","asSchema4","asArray5","withUserAgentSuffix2","getErrorMessage5","z6","zodSchema","validateTypes2","createIdGenerator2","getErrorMessage6","createIdGenerator3","asArray6","getErrorMessage7","isAbortError2","filterNullable2","UnsupportedFunctionalityError2","validateTypes3","withUserAgentSuffix3","z7","lazySchema2","zodSchema2","createIdGenerator4","createIdGenerator5","UnsupportedFunctionalityError3","safeValidateTypes5","TypeValidationError4","asSchema5","safeParseJSON4","JSONParseError2","TypeValidationError5","createIdGenerator6","withUserAgentSuffix7","createIdGenerator7","createIdGenerator8","crypto","marker","symbol","_a","_b","MCPClientError","ToolMetaSchema","z","ClientOrServerImplementationSchema","BaseParamsSchema","ResultSchema","RequestSchema","ElicitationCapabilitySchema","ServerCapabilitiesSchema","InitializeResultSchema","PaginatedResultSchema","ToolSchema","ListToolsResultSchema","TextContentSchema","ImageContentSchema","ResourceSchema","ListResourcesResultSchema","ResourceContentsSchema","TextResourceContentsSchema","BlobResourceContentsSchema","EmbeddedResourceSchema","ResourceLinkContentSchema","CallToolResultSchema","ResourceTemplateSchema","ListResourceTemplatesResultSchema","ReadResourceResultSchema","PromptReferenceSchema","ResourceReferenceSchema","CompletionArgumentSchema","CompleteResultSchema","PromptArgumentSchema","PromptSchema","ListPromptsResultSchema","PromptMessageSchema","GetPromptResultSchema","ElicitationRequestParamsSchema","ElicitResultSchema","JSONRPC_VERSION","JSONRPCRequestSchema","z2","JSONRPCResponseSchema","JSONRPCErrorSchema","JSONRPCNotificationSchema","JSONRPCMessageSchema","parseJSONRPCMessage","SafeUrlSchema","z3","OAuthTokensSchema","OAuthProtectedResourceMetadataSchema","OAuthMetadataSchema","OpenIdProviderDiscoveryMetadataSchema","OAuthClientInformationSchema","OAuthClientMetadataSchema","OAuthErrorResponseSchema","OAuthClientInformationFullSchema","AISDKError2","ServerError","InvalidClientError","InvalidGrantError","UnauthorizedClientError","OAUTH_ERRORS","parseJSON2","withUserAgentSuffix2","getRuntimeEnvironmentUserAgent2","EventSourceParserStream2","z","ResultSchema","RequestSchema","ElicitationCapabilitySchema","ServerCapabilitiesSchema","PaginatedResultSchema","ToolSchema","TextContentSchema","ImageContentSchema","ResourceSchema","ResourceContentsSchema","TextResourceContentsSchema","BlobResourceContentsSchema","EmbeddedResourceSchema","ResourceTemplateSchema","PromptReferenceSchema","PromptArgumentSchema","PromptSchema","PromptMessageSchema","JSONRPC_VERSION","JSONRPCRequestSchema","z2","JSONRPCResponseSchema","JSONRPCNotificationSchema","JSONRPCMessageSchema","z","z","Experimental_StdioMCPTransport","text","integer$1","index","index$1","integer","assert","util","exports","tty","net_1","events_1","events_1","net_1","tls_1","Buffer","require","text","integer","index","integer$1","index$1","uniqueIndex","uniqueIndex$1","primaryKey","primaryKey$1","storage","eq$1","and$1","decryptCredentialPayload$1","encryptCredentialPayload$1","node_process","node_process","selectCredentialInstanceById$2","selectCredentialInstancesForScope$2"],"sources":["../../../node_modules/.pnpm/@ai-sdk+provider@4.0.0/node_modules/@ai-sdk/provider/dist/index.js","../../../node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/index.js","../../../node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/stream.js","../../../node_modules/.pnpm/@workflow+serde@4.1.0/node_modules/@workflow/serde/dist/index.js","../../../node_modules/.pnpm/@ai-sdk+provider-utils@5.0.1_zod@4.4.3/node_modules/@ai-sdk/provider-utils/dist/index.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/get-context.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-error.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/auth-errors.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-io.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/auth-config.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/oauth.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-util.js","../../../node_modules/.pnpm/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/index.js","../../../node_modules/.pnpm/@ai-sdk+gateway@4.0.4_zod@4.4.3/node_modules/@ai-sdk/gateway/dist/index.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/entity.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/column.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/column-builder.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/table.utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/foreign-keys.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/tracing-utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/unique-constraint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/utils/array.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/enum.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/subquery.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/tracing.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/view-common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/table.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sql/sql.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/int.common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/bigint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/bigserial.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/boolean.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/char.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/cidr.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/custom.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/date.common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/date.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/double-precision.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/inet.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/integer.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/interval.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/json.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/jsonb.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/line.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/macaddr.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/macaddr8.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/numeric.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/point.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/real.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/serial.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/smallint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/smallserial.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/text.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/time.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/timestamp.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/uuid.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/varchar.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/all.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/table.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/indexes.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/primary-keys.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sql/expressions/conditions.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sql/expressions/select.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sql/functions/aggregate.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/foreign-keys.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/unique-constraint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/blob.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/custom.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/integer.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/numeric.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/real.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/text.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/all.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/table.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/indexes.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/primary-keys.js","../../tracing/dist/index.mjs","../../database/dist/index.mjs","../../../node_modules/.pnpm/ai@7.0.4_zod@4.4.3/node_modules/ai/dist/index.js","../../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js","../../../node_modules/.pnpm/@ai-sdk+mcp@2.0.3_zod@4.4.3/node_modules/@ai-sdk/mcp/dist/index.js","../../../node_modules/.pnpm/@ai-sdk+mcp@2.0.3_zod@4.4.3/node_modules/@ai-sdk/mcp/dist/mcp-stdio/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/applicability.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js","../../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json","../../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/utils.js","../../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/schemes.js","../../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js","../../mcp/dist/index.mjs","../../platform-database/dist/mcp-oauth-SRTcHMWZ.mjs","../../../node_modules/.pnpm/@ioredis+commands@1.10.0/node_modules/@ioredis/commands/built/commands.json","../../../node_modules/.pnpm/@ioredis+commands@1.10.0/node_modules/@ioredis/commands/built/index.js","../../../node_modules/.pnpm/standard-as-callback@2.1.0/node_modules/standard-as-callback/built/utils.js","../../../node_modules/.pnpm/standard-as-callback@2.1.0/node_modules/standard-as-callback/built/index.js","../../../node_modules/.pnpm/redis-errors@1.2.0/node_modules/redis-errors/lib/old.js","../../../node_modules/.pnpm/redis-errors@1.2.0/node_modules/redis-errors/lib/modern.js","../../../node_modules/.pnpm/redis-errors@1.2.0/node_modules/redis-errors/index.js","../../../node_modules/.pnpm/cluster-key-slot@1.1.1/node_modules/cluster-key-slot/lib/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/defaults.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/isArguments.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/lodash.js","../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js","../../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js","../../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/debug.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/constants/TLSProfiles.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/argumentParsers.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Command.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/errors/ClusterAllFailedError.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/ScanStream.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/autoPipelining.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Script.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/Commander.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Pipeline.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/tracing.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/transaction.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/applyMixin.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ClusterOptions.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/util.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ClusterSubscriber.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ConnectionPool.js","../../../node_modules/.pnpm/denque@2.1.0/node_modules/denque/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/DelayQueue.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ShardedSubscriber.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ClusterSubscriberGroup.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/AbstractConnector.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/StandaloneConnector.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/SentinelConnector/SentinelIterator.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/SentinelConnector/FailoverDetector.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/SentinelConnector/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/errors/MaxRetriesPerRequestError.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/errors/index.js","../../../node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/lib/parser.js","../../../node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/SubscriptionSet.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/DataHandler.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/redis/event_handler.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/redis/RedisOptions.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Redis.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/index.js","../../storage/dist/pack-artifact-DVnIKrsg.mjs","../../platform-database/dist/index.mjs","../../credentials/dist/store-4At2Wnk9.mjs","../../secrets/dist/index.mjs","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/visit.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/anchors.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/applyReviver.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/toJS.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Node.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Alias.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/createNode.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Collection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyComment.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/foldFlowLines.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyString.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringify.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyPair.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/log.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/merge.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/addPairToJSMap.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Pair.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyCollection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLMap.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/map.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLSeq.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/seq.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/string.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/null.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/bool.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyNumber.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/float.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/int.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/json/schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/binary.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/pairs.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/omap.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/bool.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/float.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/int.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/set.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/tags.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/Schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyDocument.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/Document.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/errors.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-props.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-contains-newline.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-flow-indent-check.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-map-includes.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-map.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-seq.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-end.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-collection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-collection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-empty-scalar-position.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-node.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-doc.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/composer.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-stringify.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-visit.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/lexer.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/line-counter.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/parser.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js","../../credentials/dist/index.mjs","../../workflow/dist/index.mjs"],"sourcesContent":["// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n  /**\n   * Creates an AI SDK Error.\n   *\n   * @param {Object} params - The parameters for creating the error.\n   * @param {string} params.name - The name of the error.\n   * @param {string} params.message - The error message.\n   * @param {unknown} [params.cause] - The underlying cause of the error.\n   */\n  constructor({\n    name: name15,\n    message,\n    cause\n  }) {\n    super(message);\n    this[_a] = true;\n    this.name = name15;\n    this.cause = cause;\n  }\n  /**\n   * Checks if the given error is an AI SDK Error.\n   * @param {unknown} error - The error to check.\n   * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n   */\n  static isInstance(error) {\n    return _AISDKError.hasMarker(error, marker);\n  }\n  static hasMarker(error, marker16) {\n    const markerSymbol = Symbol.for(marker16);\n    return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n  }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n  constructor({\n    message,\n    url,\n    requestBodyValues,\n    statusCode,\n    responseHeaders,\n    responseBody,\n    cause,\n    isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n    statusCode === 409 || // conflict\n    statusCode === 429 || // too many requests\n    statusCode >= 500),\n    // server error\n    data\n  }) {\n    super({ name, message, cause });\n    this[_a2] = true;\n    this.url = url;\n    this.requestBodyValues = requestBodyValues;\n    this.statusCode = statusCode;\n    this.responseHeaders = responseHeaders;\n    this.responseBody = responseBody;\n    this.isRetryable = isRetryable;\n    this.data = data;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker2);\n  }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n  // used in isInstance\n  constructor({ message = \"Empty response body\" } = {}) {\n    super({ name: name2, message });\n    this[_a3] = true;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker3);\n  }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n  if (error == null) {\n    return \"unknown error\";\n  }\n  if (typeof error === \"string\") {\n    return error;\n  }\n  if (error instanceof Error) {\n    return error.toString();\n  }\n  return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n  constructor({\n    message,\n    cause,\n    argument\n  }) {\n    super({ name: name3, message, cause });\n    this[_a4] = true;\n    this.argument = argument;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker4);\n  }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n  constructor({\n    prompt,\n    message,\n    cause\n  }) {\n    super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n    this[_a5] = true;\n    this.prompt = prompt;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker5);\n  }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n  constructor({\n    data,\n    message = `Invalid response data: ${JSON.stringify(data)}.`\n  }) {\n    super({ name: name5, message });\n    this[_a6] = true;\n    this.data = data;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker6);\n  }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n  constructor({ text, cause }) {\n    super({\n      name: name6,\n      message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n      cause\n    });\n    this[_a7] = true;\n    this.text = text;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker7);\n  }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n  // used in isInstance\n  constructor({ message }) {\n    super({ name: name7, message });\n    this[_a8] = true;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker8);\n  }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n  // used in isInstance\n  constructor({ message }) {\n    super({ name: name8, message });\n    this[_a9] = true;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker9);\n  }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n  // used in isInstance\n  constructor({\n    message = \"No content generated.\"\n  } = {}) {\n    super({ name: name9, message });\n    this[_a10] = true;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker10);\n  }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n  constructor({\n    errorName = name10,\n    modelId,\n    modelType,\n    message = `No such ${modelType}: ${modelId}`\n  }) {\n    super({ name: errorName, message });\n    this[_a11] = true;\n    this.modelId = modelId;\n    this.modelType = modelType;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker11);\n  }\n};\n\n// src/errors/no-such-provider-reference-error.ts\nvar name11 = \"AI_NoSuchProviderReferenceError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar NoSuchProviderReferenceError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n  constructor({\n    provider,\n    reference,\n    message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(\", \")}`\n  }) {\n    super({ name: name11, message });\n    this[_a12] = true;\n    this.provider = provider;\n    this.reference = reference;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker12);\n  }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name12 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TooManyEmbeddingValuesForCallError = class extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n  constructor(options) {\n    super({\n      name: name12,\n      message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n    });\n    this[_a13] = true;\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n    this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n    this.values = options.values;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker13);\n  }\n};\n\n// src/errors/type-validation-error.ts\nvar name13 = \"AI_TypeValidationError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar TypeValidationError = class _TypeValidationError extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n  constructor({\n    value,\n    cause,\n    context\n  }) {\n    let contextPrefix = \"Type validation failed\";\n    if (context == null ? void 0 : context.field) {\n      contextPrefix += ` for ${context.field}`;\n    }\n    if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n      contextPrefix += \" (\";\n      const parts = [];\n      if (context.entityName) {\n        parts.push(context.entityName);\n      }\n      if (context.entityId) {\n        parts.push(`id: \"${context.entityId}\"`);\n      }\n      contextPrefix += parts.join(\", \");\n      contextPrefix += \")\";\n    }\n    super({\n      name: name13,\n      message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n      cause\n    });\n    this[_a14] = true;\n    this.value = value;\n    this.context = context;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker14);\n  }\n  /**\n   * Wraps an error into a TypeValidationError.\n   * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n   * Otherwise, it creates a new TypeValidationError.\n   *\n   * @param {Object} params - The parameters for wrapping the error.\n   * @param {unknown} params.value - The value that failed validation.\n   * @param {unknown} params.cause - The original error or cause of the validation failure.\n   * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n   * @returns {TypeValidationError} A TypeValidationError instance.\n   */\n  static wrap({\n    value,\n    cause,\n    context\n  }) {\n    var _a16, _b16, _c;\n    if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a16 = cause.context) == null ? void 0 : _a16.field) === (context == null ? void 0 : context.field) && ((_b16 = cause.context) == null ? void 0 : _b16.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {\n      return cause;\n    }\n    return new _TypeValidationError({ value, cause, context });\n  }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name14 = \"AI_UnsupportedFunctionalityError\";\nvar marker15 = `vercel.ai.error.${name14}`;\nvar symbol15 = Symbol.for(marker15);\nvar _a15, _b15;\nvar UnsupportedFunctionalityError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {\n  constructor({\n    functionality,\n    message = `'${functionality}' functionality not supported.`\n  }) {\n    super({ name: name14, message });\n    this[_a15] = true;\n    this.functionality = functionality;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker15);\n  }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n  if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n    return true;\n  }\n  if (Array.isArray(value)) {\n    return value.every(isJSONValue);\n  }\n  if (typeof value === \"object\") {\n    return Object.entries(value).every(\n      ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n    );\n  }\n  return false;\n}\nfunction isJSONArray(value) {\n  return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n  return value != null && typeof value === \"object\" && Object.entries(value).every(\n    ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n  );\n}\nexport {\n  AISDKError,\n  APICallError,\n  EmptyResponseBodyError,\n  InvalidArgumentError,\n  InvalidPromptError,\n  InvalidResponseDataError,\n  JSONParseError,\n  LoadAPIKeyError,\n  LoadSettingError,\n  NoContentGeneratedError,\n  NoSuchModelError,\n  NoSuchProviderReferenceError,\n  TooManyEmbeddingValuesForCallError,\n  TypeValidationError,\n  UnsupportedFunctionalityError,\n  getErrorMessage,\n  isJSONArray,\n  isJSONObject,\n  isJSONValue\n};\n//# sourceMappingURL=index.js.map","class ParseError extends Error {\n  constructor(message, options) {\n    super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n  }\n}\nconst LF = 10, CR = 13, SPACE = 32;\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\n  if (typeof callbacks == \"function\")\n    throw new TypeError(\n      \"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\"\n    );\n  const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];\n  let isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType;\n  function feed(chunk) {\n    if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n      const trailing2 = processLines(chunk);\n      trailing2 !== \"\" && pendingFragments.push(trailing2);\n      return;\n    }\n    if (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n      pendingFragments.push(chunk);\n      return;\n    }\n    pendingFragments.push(chunk);\n    const input = pendingFragments.join(\"\");\n    pendingFragments.length = 0;\n    const trailing = processLines(input);\n    trailing !== \"\" && pendingFragments.push(trailing);\n  }\n  function processLines(chunk) {\n    let searchIndex = 0;\n    if (chunk.indexOf(\"\\r\") === -1) {\n      let lfIndex = chunk.indexOf(`\n`, searchIndex);\n      for (; lfIndex !== -1; ) {\n        if (searchIndex === lfIndex) {\n          dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n          continue;\n        }\n        const firstCharCode = chunk.charCodeAt(searchIndex);\n        if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n          const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n          if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n            onEvent({ id, event: eventType, data: value }), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n            continue;\n          }\n          data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n        } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(\n          chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n          lfIndex\n        ) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n        searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n      }\n      return chunk.slice(searchIndex);\n    }\n    for (; searchIndex < chunk.length; ) {\n      const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n      let lineEnd = -1;\n      if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)\n        break;\n      parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n    }\n    return chunk.slice(searchIndex);\n  }\n  function parseLine(chunk, start, end) {\n    if (start === end) {\n      dispatchEvent();\n      return;\n    }\n    const firstCharCode = chunk.charCodeAt(start);\n    if (isDataPrefix(chunk, start, firstCharCode)) {\n      const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n      data = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n      return;\n    }\n    if (isEventPrefix(chunk, start, firstCharCode)) {\n      eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n      return;\n    }\n    if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n      const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n      id = value2.includes(\"\\0\") ? void 0 : value2;\n      return;\n    }\n    if (firstCharCode === 58) {\n      if (onComment) {\n        const line2 = chunk.slice(start, end);\n        onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n      }\n      return;\n    }\n    const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n    if (fieldSeparatorIndex === -1) {\n      processField(line, \"\", line);\n      return;\n    }\n    const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n    processField(field, value, line);\n  }\n  function processField(field, value, line) {\n    switch (field) {\n      case \"event\":\n        eventType = value || void 0;\n        break;\n      case \"data\":\n        data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n        break;\n      case \"id\":\n        id = value.includes(\"\\0\") ? void 0 : value;\n        break;\n      case \"retry\":\n        /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n          new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n            type: \"invalid-retry\",\n            value,\n            line\n          })\n        );\n        break;\n      default:\n        onError(\n          new ParseError(\n            `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n            { type: \"unknown-field\", field, value, line }\n          )\n        );\n        break;\n    }\n  }\n  function dispatchEvent() {\n    dataLines > 0 && onEvent({\n      id,\n      event: eventType,\n      data\n    }), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n  }\n  function reset(options = {}) {\n    if (options.consume && pendingFragments.length > 0) {\n      const incompleteLine = pendingFragments.join(\"\");\n      parseLine(incompleteLine, 0, incompleteLine.length);\n    }\n    isFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0;\n  }\n  return { feed, reset };\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n  return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n  return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\nexport {\n  ParseError,\n  createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n  constructor({ onError, onRetry, onComment } = {}) {\n    let parser;\n    super({\n      start(controller) {\n        parser = createParser({\n          onEvent: (event) => {\n            controller.enqueue(event);\n          },\n          onError(error) {\n            onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n          },\n          onRetry,\n          onComment\n        });\n      },\n      transform(chunk) {\n        parser.feed(chunk);\n      }\n    });\n  }\n}\nexport {\n  EventSourceParserStream,\n  ParseError\n};\n//# sourceMappingURL=stream.js.map\n","/**\n * Symbol used to define custom serialization for user-defined class instances.\n * The static method should accept an instance and return serializable data.\n *\n * @example\n * ```ts\n * import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';\n *\n * class MyClass {\n *   constructor(public value: string) {}\n *\n *   static [WORKFLOW_SERIALIZE](instance: MyClass) {\n *     return { value: instance.value };\n *   }\n *\n *   static [WORKFLOW_DESERIALIZE](data: { value: string }) {\n *     return new MyClass(data.value);\n *   }\n * }\n * ```\n */\nexport const WORKFLOW_SERIALIZE = Symbol.for('workflow-serialize');\n/**\n * Symbol used to define custom deserialization for user-defined class instances.\n * The static method should accept serialized data and return a class instance.\n *\n * @see WORKFLOW_SERIALIZE for usage example\n */\nexport const WORKFLOW_DESERIALIZE = Symbol.for('workflow-deserialize');\n//# sourceMappingURL=index.js.map","// src/as-array.ts\nfunction asArray(value) {\n  return value === void 0 ? [] : Array.isArray(value) ? value : [value];\n}\n\n// src/combine-headers.ts\nfunction combineHeaders(...headers) {\n  return headers.reduce(\n    (combinedHeaders, currentHeaders) => ({\n      ...combinedHeaders,\n      ...currentHeaders != null ? currentHeaders : {}\n    }),\n    {}\n  );\n}\n\n// src/convert-async-iterator-to-readable-stream.ts\nfunction convertAsyncIteratorToReadableStream(iterator) {\n  let cancelled = false;\n  return new ReadableStream({\n    /**\n     * Called when the consumer wants to pull more data from the stream.\n     *\n     * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n     * @returns {Promise<void>}\n     */\n    async pull(controller) {\n      if (cancelled) return;\n      try {\n        const { value, done } = await iterator.next();\n        if (done) {\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n    /**\n     * Called when the consumer cancels the stream.\n     */\n    async cancel(reason) {\n      cancelled = true;\n      if (iterator.return) {\n        try {\n          await iterator.return(reason);\n        } catch (e) {\n        }\n      }\n    }\n  });\n}\n\n// src/uint8-utils.ts\nvar { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n  const base64Url = base64String.replace(/-/g, \"+\").replace(/_/g, \"/\");\n  const latin1string = atob(base64Url);\n  return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n  let latin1string = \"\";\n  for (let i = 0; i < array.length; i++) {\n    latin1string += String.fromCodePoint(array[i]);\n  }\n  return btoa(latin1string);\n}\nfunction convertToBase64(value) {\n  return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n\n// src/convert-inline-file-data-to-uint8-array.ts\nfunction convertInlineFileDataToUint8Array(data) {\n  if (data.type === \"text\") {\n    return new TextEncoder().encode(data.text);\n  }\n  if (data.data instanceof Uint8Array) {\n    return data.data;\n  }\n  if (data.data instanceof ArrayBuffer) {\n    return new Uint8Array(data.data);\n  }\n  return convertBase64ToUint8Array(data.data);\n}\n\n// src/convert-image-model-file-to-data-uri.ts\nfunction convertImageModelFileToDataUri(file) {\n  if (file.type === \"url\") return file.url;\n  return `data:${file.mediaType};base64,${typeof file.data === \"string\" ? file.data : convertUint8ArrayToBase64(file.data)}`;\n}\n\n// src/convert-to-form-data.ts\nfunction convertToFormData(input, options = {}) {\n  const { useArrayBrackets = true } = options;\n  const formData = new FormData();\n  for (const [key, value] of Object.entries(input)) {\n    if (value == null) {\n      continue;\n    }\n    if (Array.isArray(value)) {\n      if (value.length === 1) {\n        formData.append(key, value[0]);\n        continue;\n      }\n      const arrayKey = useArrayBrackets ? `${key}[]` : key;\n      for (const item of value) {\n        formData.append(arrayKey, item);\n      }\n      continue;\n    }\n    formData.append(key, value);\n  }\n  return formData;\n}\n\n// src/create-tool-name-mapping.ts\nfunction createToolNameMapping({\n  tools = [],\n  providerToolNames\n}) {\n  const customToolNameToProviderToolName = {};\n  const providerToolNameToCustomToolName = {};\n  for (const tool2 of tools) {\n    if (tool2.type === \"provider\" && tool2.id in providerToolNames) {\n      const providerToolName = providerToolNames[tool2.id];\n      customToolNameToProviderToolName[tool2.name] = providerToolName;\n      providerToolNameToCustomToolName[providerToolName] = tool2.name;\n    }\n  }\n  return {\n    toProviderToolName: (customToolName) => {\n      var _a2;\n      return (_a2 = customToolNameToProviderToolName[customToolName]) != null ? _a2 : customToolName;\n    },\n    toCustomToolName: (providerToolName) => {\n      var _a2;\n      return (_a2 = providerToolNameToCustomToolName[providerToolName]) != null ? _a2 : providerToolName;\n    }\n  };\n}\n\n// src/delay.ts\nasync function delay(delayInMs, options) {\n  if (delayInMs == null) {\n    return Promise.resolve();\n  }\n  const signal = options == null ? void 0 : options.abortSignal;\n  return new Promise((resolve2, reject) => {\n    if (signal == null ? void 0 : signal.aborted) {\n      reject(createAbortError());\n      return;\n    }\n    const timeoutId = setTimeout(() => {\n      cleanup();\n      resolve2();\n    }, delayInMs);\n    const cleanup = () => {\n      clearTimeout(timeoutId);\n      signal == null ? void 0 : signal.removeEventListener(\"abort\", onAbort);\n    };\n    const onAbort = () => {\n      cleanup();\n      reject(createAbortError());\n    };\n    signal == null ? void 0 : signal.addEventListener(\"abort\", onAbort);\n  });\n}\nfunction createAbortError() {\n  return new DOMException(\"Delay was aborted\", \"AbortError\");\n}\n\n// src/delayed-promise.ts\nvar DelayedPromise = class {\n  constructor() {\n    this.status = { type: \"pending\" };\n    this._resolve = void 0;\n    this._reject = void 0;\n  }\n  get promise() {\n    if (this._promise) {\n      return this._promise;\n    }\n    this._promise = new Promise((resolve2, reject) => {\n      if (this.status.type === \"resolved\") {\n        resolve2(this.status.value);\n      } else if (this.status.type === \"rejected\") {\n        reject(this.status.error);\n      }\n      this._resolve = resolve2;\n      this._reject = reject;\n    });\n    return this._promise;\n  }\n  resolve(value) {\n    var _a2;\n    this.status = { type: \"resolved\", value };\n    if (this._promise) {\n      (_a2 = this._resolve) == null ? void 0 : _a2.call(this, value);\n    }\n  }\n  reject(error) {\n    var _a2;\n    this.status = { type: \"rejected\", error };\n    if (this._promise) {\n      (_a2 = this._reject) == null ? void 0 : _a2.call(this, error);\n    }\n  }\n  isResolved() {\n    return this.status.type === \"resolved\";\n  }\n  isRejected() {\n    return this.status.type === \"rejected\";\n  }\n  isPending() {\n    return this.status.type === \"pending\";\n  }\n};\n\n// src/detect-media-type.ts\nvar imageMediaTypeSignatures = [\n  {\n    mediaType: \"image/gif\",\n    bytesPrefix: [71, 73, 70]\n    // GIF\n  },\n  {\n    mediaType: \"image/png\",\n    bytesPrefix: [137, 80, 78, 71]\n    // PNG\n  },\n  {\n    mediaType: \"image/jpeg\",\n    bytesPrefix: [255, 216]\n    // JPEG\n  },\n  {\n    mediaType: \"image/webp\",\n    bytesPrefix: [\n      82,\n      73,\n      70,\n      70,\n      // \"RIFF\"\n      null,\n      null,\n      null,\n      null,\n      // file size (variable)\n      87,\n      69,\n      66,\n      80\n      // \"WEBP\"\n    ]\n  },\n  {\n    mediaType: \"image/bmp\",\n    bytesPrefix: [66, 77]\n  },\n  {\n    mediaType: \"image/tiff\",\n    bytesPrefix: [73, 73, 42, 0]\n  },\n  {\n    mediaType: \"image/tiff\",\n    bytesPrefix: [77, 77, 0, 42]\n  },\n  {\n    mediaType: \"image/avif\",\n    bytesPrefix: [\n      0,\n      0,\n      0,\n      32,\n      102,\n      116,\n      121,\n      112,\n      97,\n      118,\n      105,\n      102\n    ]\n  },\n  {\n    mediaType: \"image/heic\",\n    bytesPrefix: [\n      0,\n      0,\n      0,\n      32,\n      102,\n      116,\n      121,\n      112,\n      104,\n      101,\n      105,\n      99\n    ]\n  }\n];\nvar documentMediaTypeSignatures = [\n  {\n    mediaType: \"application/pdf\",\n    bytesPrefix: [37, 80, 68, 70]\n    // %PDF\n  }\n];\nvar audioMediaTypeSignatures = [\n  {\n    mediaType: \"audio/mpeg\",\n    bytesPrefix: [255, 251]\n  },\n  {\n    mediaType: \"audio/mpeg\",\n    bytesPrefix: [255, 250]\n  },\n  {\n    mediaType: \"audio/mpeg\",\n    bytesPrefix: [255, 243]\n  },\n  {\n    mediaType: \"audio/mpeg\",\n    bytesPrefix: [255, 242]\n  },\n  {\n    mediaType: \"audio/mpeg\",\n    bytesPrefix: [255, 227]\n  },\n  {\n    mediaType: \"audio/mpeg\",\n    bytesPrefix: [255, 226]\n  },\n  {\n    mediaType: \"audio/wav\",\n    bytesPrefix: [\n      82,\n      // R\n      73,\n      // I\n      70,\n      // F\n      70,\n      // F\n      null,\n      null,\n      null,\n      null,\n      87,\n      // W\n      65,\n      // A\n      86,\n      // V\n      69\n      // E\n    ]\n  },\n  {\n    mediaType: \"audio/ogg\",\n    bytesPrefix: [79, 103, 103, 83]\n  },\n  {\n    mediaType: \"audio/flac\",\n    bytesPrefix: [102, 76, 97, 67]\n  },\n  {\n    mediaType: \"audio/aac\",\n    bytesPrefix: [64, 21, 0, 0]\n  },\n  {\n    mediaType: \"audio/mp4\",\n    bytesPrefix: [102, 116, 121, 112]\n  },\n  {\n    mediaType: \"audio/webm\",\n    bytesPrefix: [26, 69, 223, 163]\n  }\n];\nvar videoMediaTypeSignatures = [\n  {\n    mediaType: \"video/mp4\",\n    bytesPrefix: [\n      0,\n      0,\n      0,\n      null,\n      102,\n      116,\n      121,\n      112\n      // ftyp\n    ]\n  },\n  {\n    mediaType: \"video/webm\",\n    bytesPrefix: [26, 69, 223, 163]\n    // EBML\n  },\n  {\n    mediaType: \"video/quicktime\",\n    bytesPrefix: [\n      0,\n      0,\n      0,\n      20,\n      102,\n      116,\n      121,\n      112,\n      113,\n      116\n      // ftypqt\n    ]\n  },\n  {\n    mediaType: \"video/x-msvideo\",\n    bytesPrefix: [82, 73, 70, 70]\n    // RIFF (AVI)\n  }\n];\nvar stripID3 = (data) => {\n  const bytes = typeof data === \"string\" ? convertBase64ToUint8Array(data) : data;\n  const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;\n  return bytes.slice(id3Size + 10);\n};\nfunction stripID3TagsIfPresent(data) {\n  const hasId3 = typeof data === \"string\" && data.startsWith(\"SUQz\") || typeof data !== \"string\" && data.length > 10 && data[0] === 73 && // 'I'\n  data[1] === 68 && // 'D'\n  data[2] === 51;\n  return hasId3 ? stripID3(data) : data;\n}\nfunction detectMediaTypeBySignatures({\n  data,\n  signatures\n}) {\n  const processedData = stripID3TagsIfPresent(data);\n  const bytes = typeof processedData === \"string\" ? convertBase64ToUint8Array(\n    processedData.substring(0, Math.min(processedData.length, 24))\n  ) : processedData;\n  for (const signature of signatures) {\n    if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every(\n      (byte, index) => byte === null || bytes[index] === byte\n    )) {\n      return signature.mediaType;\n    }\n  }\n  return void 0;\n}\nvar topLevelSignatureTables = {\n  image: imageMediaTypeSignatures,\n  audio: audioMediaTypeSignatures,\n  video: videoMediaTypeSignatures,\n  application: documentMediaTypeSignatures\n};\nfunction detectMediaType({\n  data,\n  topLevelType\n}) {\n  if (topLevelType === void 0) {\n    return detectMediaTypeBySignatures({\n      data,\n      signatures: [\n        ...imageMediaTypeSignatures,\n        ...documentMediaTypeSignatures,\n        ...audioMediaTypeSignatures,\n        ...videoMediaTypeSignatures\n      ]\n    });\n  }\n  const signatures = topLevelSignatureTables[topLevelType];\n  if (signatures === void 0) {\n    return void 0;\n  }\n  return detectMediaTypeBySignatures({ data, signatures });\n}\nfunction getTopLevelMediaType(mediaType) {\n  const slashIndex = mediaType.indexOf(\"/\");\n  return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);\n}\nfunction isFullMediaType(mediaType) {\n  const slashIndex = mediaType.indexOf(\"/\");\n  if (slashIndex === -1) {\n    return false;\n  }\n  const subtype = mediaType.substring(slashIndex + 1);\n  return subtype.length > 0 && subtype !== \"*\";\n}\n\n// src/cancel-response-body.ts\nasync function cancelResponseBody(response) {\n  var _a2;\n  try {\n    await ((_a2 = response.body) == null ? void 0 : _a2.cancel());\n  } catch (e) {\n  }\n}\n\n// src/download-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_DownloadError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {\n  constructor({\n    url,\n    statusCode,\n    statusText,\n    cause,\n    message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`\n  }) {\n    super({ name, message, cause });\n    this[_a] = true;\n    this.url = url;\n    this.statusCode = statusCode;\n    this.statusText = statusText;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker);\n  }\n};\n\n// src/is-browser-runtime.ts\nfunction isBrowserRuntime(globalThisAny = globalThis) {\n  return globalThisAny.window != null;\n}\n\n// src/validate-download-url.ts\nfunction validateDownloadUrl(url) {\n  let parsed;\n  try {\n    parsed = new URL(url);\n  } catch (e) {\n    throw new DownloadError({\n      url,\n      message: `Invalid URL: ${url}`\n    });\n  }\n  if (parsed.protocol === \"data:\") {\n    return;\n  }\n  if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n    throw new DownloadError({\n      url,\n      message: `URL scheme must be http, https, or data, got ${parsed.protocol}`\n    });\n  }\n  const hostname = parsed.hostname.toLowerCase().replace(/\\.+$/, \"\");\n  if (!hostname) {\n    throw new DownloadError({\n      url,\n      message: `URL must have a hostname`\n    });\n  }\n  if (hostname === \"localhost\" || hostname.endsWith(\".local\") || hostname.endsWith(\".localhost\")) {\n    throw new DownloadError({\n      url,\n      message: `URL with hostname ${hostname} is not allowed`\n    });\n  }\n  if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n    const ipv6 = hostname.slice(1, -1);\n    if (isPrivateIPv6(ipv6)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IPv6 address ${hostname} is not allowed`\n      });\n    }\n    return;\n  }\n  if (isIPv4(hostname)) {\n    if (isPrivateIPv4(hostname)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IP address ${hostname} is not allowed`\n      });\n    }\n    return;\n  }\n}\nfunction isIPv4(hostname) {\n  const parts = hostname.split(\".\");\n  if (parts.length !== 4) return false;\n  return parts.every((part) => {\n    const num = Number(part);\n    return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;\n  });\n}\nfunction isPrivateIPv4(ip) {\n  const parts = ip.split(\".\").map(Number);\n  const [a, b, c] = parts;\n  if (a === 0) return true;\n  if (a === 10) return true;\n  if (a === 100 && b >= 64 && b <= 127) return true;\n  if (a === 127) return true;\n  if (a === 169 && b === 254) return true;\n  if (a === 172 && b >= 16 && b <= 31) return true;\n  if (a === 192 && b === 0 && c === 0) return true;\n  if (a === 192 && b === 168) return true;\n  if (a === 198 && (b === 18 || b === 19)) return true;\n  if (a >= 240) return true;\n  return false;\n}\nfunction parseIPv6(ip) {\n  let address = ip.toLowerCase();\n  const zoneIndex = address.indexOf(\"%\");\n  if (zoneIndex !== -1) {\n    address = address.slice(0, zoneIndex);\n  }\n  const halves = address.split(\"::\");\n  if (halves.length > 2) return null;\n  const toGroups = (segment) => {\n    if (segment === \"\") return [];\n    const groups = [];\n    const parts = segment.split(\":\");\n    for (let i = 0; i < parts.length; i++) {\n      const part = parts[i];\n      if (part.includes(\".\")) {\n        if (i !== parts.length - 1 || !isIPv4(part)) return null;\n        const [a, b, c, d] = part.split(\".\").map(Number);\n        groups.push(a << 8 | b, c << 8 | d);\n        continue;\n      }\n      if (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n      groups.push(parseInt(part, 16));\n    }\n    return groups;\n  };\n  const head = toGroups(halves[0]);\n  if (head === null) return null;\n  if (halves.length === 2) {\n    const tail = toGroups(halves[1]);\n    if (tail === null) return null;\n    const fill = 8 - head.length - tail.length;\n    if (fill < 0) return null;\n    return [...head, ...new Array(fill).fill(0), ...tail];\n  }\n  return head.length === 8 ? head : null;\n}\nfunction isPrivateIPv6(ip) {\n  const groups = parseIPv6(ip);\n  if (groups === null) return true;\n  const topZero = (count) => groups.slice(0, count).every((group) => group === 0);\n  if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;\n  if ((groups[0] & 65024) === 64512) return true;\n  if ((groups[0] & 65472) === 65152) return true;\n  if ((groups[0] & 65472) === 65216) return true;\n  if ((groups[0] & 65280) === 65280) return true;\n  const embedsIPv4 = (\n    // ::/96 — IPv4-compatible (deprecated)\n    topZero(6) || // ::ffff:0:0/96 — IPv4-mapped (ffff in group 5)\n    topZero(5) && groups[5] === 65535 || // ::ffff:0:0/96 — IPv4-translated form (ffff in group 4, group 5 zero)\n    topZero(4) && groups[4] === 65535 && groups[5] === 0 || // 64:ff9b::/96 — NAT64 well-known prefix\n    groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || // 64:ff9b:1::/48 — NAT64 local-use prefix\n    groups[0] === 100 && groups[1] === 65435 && groups[2] === 1\n  );\n  if (embedsIPv4) {\n    const a = groups[6] >> 8 & 255;\n    const b = groups[6] & 255;\n    const c = groups[7] >> 8 & 255;\n    const d = groups[7] & 255;\n    return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n  }\n  return false;\n}\n\n// src/fetch-with-validated-redirects.ts\nvar MAX_DOWNLOAD_REDIRECTS = 10;\nasync function fetchWithValidatedRedirects({\n  url,\n  headers,\n  abortSignal,\n  maxRedirects = MAX_DOWNLOAD_REDIRECTS\n}) {\n  const baseInit = { signal: abortSignal };\n  if (headers !== void 0) {\n    baseInit.headers = headers;\n  }\n  let currentUrl = url;\n  for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {\n    validateDownloadUrl(currentUrl);\n    const response = await fetch(currentUrl, {\n      ...baseInit,\n      redirect: \"manual\"\n    });\n    if (response.type === \"opaqueredirect\") {\n      if (!isBrowserRuntime()) {\n        throw new DownloadError({\n          url,\n          message: `Redirect from ${currentUrl} could not be validated and was blocked`\n        });\n      }\n      return await fetch(currentUrl, { ...baseInit, redirect: \"follow\" });\n    }\n    const location = response.headers.get(\"location\");\n    if (response.status >= 300 && response.status < 400 && location) {\n      await cancelResponseBody(response);\n      currentUrl = new URL(location, currentUrl).toString();\n      continue;\n    }\n    return response;\n  }\n  throw new DownloadError({\n    url,\n    message: `Too many redirects (max ${maxRedirects})`\n  });\n}\n\n// src/read-response-with-size-limit.ts\nvar DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\nasync function readResponseWithSizeLimit({\n  response,\n  url,\n  maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE\n}) {\n  const contentLength = response.headers.get(\"content-length\");\n  if (contentLength != null) {\n    const length = parseInt(contentLength, 10);\n    if (!isNaN(length) && length > maxBytes) {\n      await cancelResponseBody(response);\n      throw new DownloadError({\n        url,\n        message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`\n      });\n    }\n  }\n  const body = response.body;\n  if (body == null) {\n    return new Uint8Array(0);\n  }\n  const reader = body.getReader();\n  const chunks = [];\n  let totalBytes = 0;\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) {\n        break;\n      }\n      totalBytes += value.length;\n      if (totalBytes > maxBytes) {\n        throw new DownloadError({\n          url,\n          message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`\n        });\n      }\n      chunks.push(value);\n    }\n  } finally {\n    try {\n      await reader.cancel();\n    } finally {\n      reader.releaseLock();\n    }\n  }\n  const result = new Uint8Array(totalBytes);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.length;\n  }\n  return result;\n}\n\n// src/download-blob.ts\nasync function downloadBlob(url, options) {\n  var _a2, _b2;\n  try {\n    const response = await fetchWithValidatedRedirects({\n      url,\n      abortSignal: options == null ? void 0 : options.abortSignal\n    });\n    if (!response.ok) {\n      await cancelResponseBody(response);\n      throw new DownloadError({\n        url,\n        statusCode: response.status,\n        statusText: response.statusText\n      });\n    }\n    const data = await readResponseWithSizeLimit({\n      response,\n      url,\n      maxBytes: (_a2 = options == null ? void 0 : options.maxBytes) != null ? _a2 : DEFAULT_MAX_DOWNLOAD_SIZE\n    });\n    const contentType = (_b2 = response.headers.get(\"content-type\")) != null ? _b2 : void 0;\n    return new Blob([data], contentType ? { type: contentType } : void 0);\n  } catch (error) {\n    if (DownloadError.isInstance(error)) {\n      throw error;\n    }\n    throw new DownloadError({ url, cause: error });\n  }\n}\n\n// src/extract-lines.ts\nfunction extractLines({\n  text,\n  startLine,\n  endLine\n}) {\n  if (startLine == null && endLine == null) return text;\n  const lineEnding = text.includes(\"\\r\\n\") ? \"\\r\\n\" : text.includes(\"\\n\") ? \"\\n\" : text.includes(\"\\r\") ? \"\\r\" : \"\\n\";\n  const lines = text.split(lineEnding);\n  const start = Math.max(1, startLine != null ? startLine : 1) - 1;\n  const end = Math.min(lines.length, endLine != null ? endLine : lines.length);\n  return lines.slice(start, end).join(lineEnding);\n}\n\n// src/extract-response-headers.ts\nfunction extractResponseHeaders(response) {\n  return Object.fromEntries([...response.headers]);\n}\n\n// src/filter-nullable.ts\nfunction filterNullable(...values) {\n  return values.filter((value) => value != null);\n}\n\n// src/generate-id.ts\nimport { InvalidArgumentError } from \"@ai-sdk/provider\";\nvar createIdGenerator = ({\n  prefix,\n  size = 16,\n  alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n  separator = \"-\"\n} = {}) => {\n  const generator = () => {\n    const alphabetLength = alphabet.length;\n    const chars = new Array(size);\n    for (let i = 0; i < size; i++) {\n      chars[i] = alphabet[Math.random() * alphabetLength | 0];\n    }\n    return chars.join(\"\");\n  };\n  if (prefix == null) {\n    return generator;\n  }\n  if (alphabet.includes(separator)) {\n    throw new InvalidArgumentError({\n      argument: \"separator\",\n      message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n    });\n  }\n  return () => `${prefix}${separator}${generator()}`;\n};\nvar generateId = createIdGenerator();\n\n// src/get-error-message.ts\nimport { getErrorMessage } from \"@ai-sdk/provider\";\n\n// src/get-from-api.ts\nimport { APICallError as APICallError2 } from \"@ai-sdk/provider\";\n\n// src/handle-fetch-error.ts\nimport { APICallError } from \"@ai-sdk/provider\";\n\n// src/is-abort-error.ts\nfunction isAbortError(error) {\n  return (error instanceof Error || error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || // Next.js\n  error.name === \"TimeoutError\");\n}\n\n// src/handle-fetch-error.ts\nvar FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nvar BUN_ERROR_CODES = [\n  \"ConnectionRefused\",\n  \"ConnectionClosed\",\n  \"FailedToOpenSocket\",\n  \"ECONNRESET\",\n  \"ECONNREFUSED\",\n  \"ETIMEDOUT\",\n  \"EPIPE\"\n];\nfunction isBunNetworkError(error) {\n  if (!(error instanceof Error)) {\n    return false;\n  }\n  const code = error.code;\n  if (typeof code === \"string\" && BUN_ERROR_CODES.includes(code)) {\n    return true;\n  }\n  return false;\n}\nfunction handleFetchError({\n  error,\n  url,\n  requestBodyValues\n}) {\n  if (isAbortError(error)) {\n    return error;\n  }\n  if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n    const cause = error.cause;\n    if (cause != null) {\n      return new APICallError({\n        message: `Cannot connect to API: ${cause.message}`,\n        cause,\n        url,\n        requestBodyValues,\n        isRetryable: true\n        // retry when network error\n      });\n    }\n  }\n  if (isBunNetworkError(error)) {\n    return new APICallError({\n      message: `Cannot connect to API: ${error.message}`,\n      cause: error,\n      url,\n      requestBodyValues,\n      isRetryable: true\n    });\n  }\n  return error;\n}\n\n// src/get-runtime-environment-user-agent.ts\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n  var _a2, _b2, _c;\n  if (globalThisAny.window) {\n    return `runtime/browser`;\n  }\n  if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) {\n    return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n  }\n  if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) {\n    return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n  }\n  if (globalThisAny.EdgeRuntime) {\n    return `runtime/vercel-edge`;\n  }\n  return \"runtime/unknown\";\n}\n\n// src/normalize-headers.ts\nfunction normalizeHeaders(headers) {\n  if (headers == null) {\n    return {};\n  }\n  const normalized = {};\n  if (headers instanceof Headers) {\n    headers.forEach((value, key) => {\n      normalized[key.toLowerCase()] = value;\n    });\n  } else {\n    if (!Array.isArray(headers)) {\n      headers = Object.entries(headers);\n    }\n    for (const [key, value] of headers) {\n      if (value != null) {\n        normalized[key.toLowerCase()] = value;\n      }\n    }\n  }\n  return normalized;\n}\n\n// src/with-user-agent-suffix.ts\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n  const normalizedHeaders = new Headers(normalizeHeaders(headers));\n  const currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n  normalizedHeaders.set(\n    \"user-agent\",\n    [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \")\n  );\n  return Object.fromEntries(normalizedHeaders.entries());\n}\n\n// src/version.ts\nvar VERSION = true ? \"5.0.1\" : \"0.0.0-test\";\n\n// src/get-from-api.ts\nvar getOriginalFetch = () => globalThis.fetch;\nvar getFromApi = async ({\n  url,\n  headers = {},\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch: fetch2 = getOriginalFetch()\n}) => {\n  try {\n    const response = await fetch2(url, {\n      method: \"GET\",\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent()\n      ),\n      signal: abortSignal\n    });\n    const responseHeaders = extractResponseHeaders(response);\n    if (!response.ok) {\n      let errorInformation;\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: {}\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError2.isInstance(error)) {\n          throw error;\n        }\n        throw new APICallError2({\n          message: \"Failed to process error response\",\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: {}\n        });\n      }\n      throw errorInformation.value;\n    }\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: {}\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError2.isInstance(error)) {\n          throw error;\n        }\n      }\n      throw new APICallError2({\n        message: \"Failed to process successful response\",\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: {}\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: {} });\n  }\n};\n\n// src/inject-json-instruction.ts\nvar DEFAULT_SCHEMA_PREFIX = \"JSON schema:\";\nvar DEFAULT_SCHEMA_SUFFIX = \"You MUST answer with a JSON object that matches the JSON schema above.\";\nvar DEFAULT_GENERIC_SUFFIX = \"You MUST answer with JSON.\";\nfunction injectJsonInstruction({\n  prompt,\n  schema,\n  schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,\n  schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX\n}) {\n  return [\n    prompt != null && prompt.length > 0 ? prompt : void 0,\n    prompt != null && prompt.length > 0 ? \"\" : void 0,\n    // add a newline if prompt is not null\n    schemaPrefix,\n    schema != null ? JSON.stringify(schema) : void 0,\n    schemaSuffix\n  ].filter((line) => line != null).join(\"\\n\");\n}\nfunction injectJsonInstructionIntoMessages({\n  messages,\n  schema,\n  schemaPrefix,\n  schemaSuffix\n}) {\n  var _a2, _b2;\n  const systemMessage = ((_a2 = messages[0]) == null ? void 0 : _a2.role) === \"system\" ? { ...messages[0] } : { role: \"system\", content: \"\" };\n  systemMessage.content = injectJsonInstruction({\n    prompt: systemMessage.content,\n    schema,\n    schemaPrefix,\n    schemaSuffix\n  });\n  return [\n    systemMessage,\n    ...((_b2 = messages[0]) == null ? void 0 : _b2.role) === \"system\" ? messages.slice(1) : messages\n  ];\n}\n\n// src/is-buffer.ts\nfunction isBuffer(value) {\n  var _a2, _b2;\n  return (_b2 = (_a2 = globalThis.Buffer) == null ? void 0 : _a2.isBuffer(value)) != null ? _b2 : false;\n}\n\n// src/is-same-origin.ts\nfunction isSameOrigin(url, baseUrl) {\n  try {\n    return new URL(url).origin === new URL(baseUrl).origin;\n  } catch (e) {\n    return false;\n  }\n}\n\n// src/is-non-nullable.ts\nfunction isNonNullable(value) {\n  return value != null;\n}\n\n// src/is-provider-reference.ts\nfunction isProviderReference(data) {\n  return typeof data === \"object\" && data !== null && !(data instanceof Uint8Array) && !(data instanceof URL) && !(data instanceof ArrayBuffer) && !isBuffer(data) && !(\"type\" in data);\n}\n\n// src/is-url-supported.ts\nfunction isUrlSupported({\n  mediaType,\n  url,\n  supportedUrls\n}) {\n  url = url.toLowerCase();\n  mediaType = mediaType.toLowerCase();\n  const isTopLevelOnly = !mediaType.includes(\"/\");\n  return Object.entries(supportedUrls).map(([key, value]) => {\n    const mediaType2 = key.toLowerCase();\n    return mediaType2 === \"*\" || mediaType2 === \"*/*\" ? { mediaTypePrefix: \"\", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\\*/, \"\"), regexes: value };\n  }).filter(({ mediaTypePrefix }) => {\n    if (mediaTypePrefix === \"\") {\n      return true;\n    }\n    if (isTopLevelOnly) {\n      return `${mediaType}/` === mediaTypePrefix;\n    }\n    return mediaType.startsWith(mediaTypePrefix);\n  }).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));\n}\n\n// src/load-api-key.ts\nimport { LoadAPIKeyError } from \"@ai-sdk/provider\";\nfunction loadApiKey({\n  apiKey,\n  environmentVariableName,\n  apiKeyParameterName = \"apiKey\",\n  description\n}) {\n  if (typeof apiKey === \"string\") {\n    return apiKey;\n  }\n  if (apiKey != null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string.`\n    });\n  }\n  if (typeof process === \"undefined\") {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`\n    });\n  }\n  apiKey = process.env[environmentVariableName];\n  if (apiKey == null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`\n    });\n  }\n  if (typeof apiKey !== \"string\") {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n    });\n  }\n  return apiKey;\n}\n\n// src/load-optional-setting.ts\nfunction loadOptionalSetting({\n  settingValue,\n  environmentVariableName\n}) {\n  if (typeof settingValue === \"string\") {\n    return settingValue;\n  }\n  if (settingValue != null || typeof process === \"undefined\") {\n    return void 0;\n  }\n  settingValue = process.env[environmentVariableName];\n  if (settingValue == null || typeof settingValue !== \"string\") {\n    return void 0;\n  }\n  return settingValue;\n}\n\n// src/load-setting.ts\nimport { LoadSettingError } from \"@ai-sdk/provider\";\nfunction loadSetting({\n  settingValue,\n  environmentVariableName,\n  settingName,\n  description\n}) {\n  if (typeof settingValue === \"string\") {\n    return settingValue;\n  }\n  if (settingValue != null) {\n    throw new LoadSettingError({\n      message: `${description} setting must be a string.`\n    });\n  }\n  if (typeof process === \"undefined\") {\n    throw new LoadSettingError({\n      message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables are not supported in this environment.`\n    });\n  }\n  settingValue = process.env[environmentVariableName];\n  if (settingValue == null) {\n    throw new LoadSettingError({\n      message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`\n    });\n  }\n  if (typeof settingValue !== \"string\") {\n    throw new LoadSettingError({\n      message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n    });\n  }\n  return settingValue;\n}\n\n// src/map-reasoning-to-provider.ts\nfunction isCustomReasoning(reasoning) {\n  return reasoning !== void 0 && reasoning !== \"provider-default\";\n}\nfunction mapReasoningToProviderEffort({\n  reasoning,\n  effortMap,\n  warnings\n}) {\n  const mapped = effortMap[reasoning];\n  if (mapped == null) {\n    warnings.push({\n      type: \"unsupported\",\n      feature: \"reasoning\",\n      details: `reasoning \"${reasoning}\" is not supported by this model.`\n    });\n    return void 0;\n  }\n  if (mapped !== reasoning) {\n    warnings.push({\n      type: \"compatibility\",\n      feature: \"reasoning\",\n      details: `reasoning \"${reasoning}\" is not directly supported by this model. mapped to effort \"${mapped}\".`\n    });\n  }\n  return mapped;\n}\nvar DEFAULT_REASONING_BUDGET_PERCENTAGES = {\n  minimal: 0.02,\n  low: 0.1,\n  medium: 0.3,\n  high: 0.6,\n  xhigh: 0.9\n};\nfunction mapReasoningToProviderBudget({\n  reasoning,\n  maxOutputTokens,\n  maxReasoningBudget,\n  minReasoningBudget = 1024,\n  budgetPercentages = DEFAULT_REASONING_BUDGET_PERCENTAGES,\n  warnings\n}) {\n  const pct = budgetPercentages[reasoning];\n  if (pct == null) {\n    warnings.push({\n      type: \"unsupported\",\n      feature: \"reasoning\",\n      details: `reasoning \"${reasoning}\" is not supported by this model.`\n    });\n    return void 0;\n  }\n  return Math.min(\n    maxReasoningBudget,\n    Math.max(minReasoningBudget, Math.round(maxOutputTokens * pct))\n  );\n}\n\n// src/media-type-to-extension.ts\nfunction mediaTypeToExtension(mediaType) {\n  var _a2;\n  const [_type, subtype = \"\"] = mediaType.toLowerCase().split(\"/\");\n  return (_a2 = {\n    mpeg: \"mp3\",\n    \"x-wav\": \"wav\",\n    opus: \"ogg\",\n    mp4: \"m4a\",\n    \"x-m4a\": \"m4a\"\n  }[subtype]) != null ? _a2 : subtype;\n}\n\n// src/parse-json.ts\nimport {\n  JSONParseError,\n  TypeValidationError as TypeValidationError3\n} from \"@ai-sdk/provider\";\n\n// src/secure-json-parse.ts\nvar suspectProtoRx = /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nvar suspectConstructorRx = /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\nfunction _parse(text) {\n  const obj = JSON.parse(text);\n  if (obj === null || typeof obj !== \"object\") {\n    return obj;\n  }\n  if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {\n    return obj;\n  }\n  return filter(obj);\n}\nfunction filter(obj) {\n  let next = [obj];\n  while (next.length) {\n    const nodes = next;\n    next = [];\n    for (const node of nodes) {\n      if (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) {\n        throw new SyntaxError(\"Object contains forbidden prototype property\");\n      }\n      if (Object.prototype.hasOwnProperty.call(node, \"constructor\") && node.constructor !== null && typeof node.constructor === \"object\" && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) {\n        throw new SyntaxError(\"Object contains forbidden prototype property\");\n      }\n      for (const key in node) {\n        const value = node[key];\n        if (value && typeof value === \"object\") {\n          next.push(value);\n        }\n      }\n    }\n  }\n  return obj;\n}\nfunction secureJsonParse(text) {\n  const { stackTraceLimit } = Error;\n  try {\n    Error.stackTraceLimit = 0;\n  } catch (e) {\n    return _parse(text);\n  }\n  try {\n    return _parse(text);\n  } finally {\n    Error.stackTraceLimit = stackTraceLimit;\n  }\n}\n\n// src/validate-types.ts\nimport {\n  TypeValidationError as TypeValidationError2\n} from \"@ai-sdk/provider\";\n\n// src/schema.ts\nimport { TypeValidationError } from \"@ai-sdk/provider\";\nimport * as z4 from \"zod/v4\";\n\n// src/add-additional-properties-to-json-schema.ts\nfunction addAdditionalPropertiesToJsonSchema(jsonSchema2) {\n  if (jsonSchema2.type === \"object\" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes(\"object\")) {\n    jsonSchema2.additionalProperties = false;\n    const { properties } = jsonSchema2;\n    if (properties != null) {\n      for (const key of Object.keys(properties)) {\n        properties[key] = visit(properties[key]);\n      }\n    }\n  }\n  if (jsonSchema2.items != null) {\n    jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);\n  }\n  if (jsonSchema2.anyOf != null) {\n    jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);\n  }\n  if (jsonSchema2.allOf != null) {\n    jsonSchema2.allOf = jsonSchema2.allOf.map(visit);\n  }\n  if (jsonSchema2.oneOf != null) {\n    jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);\n  }\n  const { definitions } = jsonSchema2;\n  if (definitions != null) {\n    for (const key of Object.keys(definitions)) {\n      definitions[key] = visit(definitions[key]);\n    }\n  }\n  return jsonSchema2;\n}\nfunction visit(def) {\n  if (typeof def === \"boolean\") return def;\n  return addAdditionalPropertiesToJsonSchema(def);\n}\n\n// src/to-json-schema/zod3-to-json-schema/options.ts\nvar ignoreOverride = /* @__PURE__ */ Symbol(\n  \"Let zodToJsonSchema decide on which parser to use\"\n);\nvar defaultOptions = {\n  name: void 0,\n  $refStrategy: \"root\",\n  basePath: [\"#\"],\n  effectStrategy: \"input\",\n  pipeStrategy: \"all\",\n  dateStrategy: \"format:date-time\",\n  mapStrategy: \"entries\",\n  removeAdditionalStrategy: \"passthrough\",\n  allowedAdditionalProperties: true,\n  rejectedAdditionalProperties: false,\n  definitionPath: \"definitions\",\n  strictUnions: false,\n  definitions: {},\n  errorMessages: false,\n  patternStrategy: \"escape\",\n  applyRegexFlags: false,\n  emailStrategy: \"format:email\",\n  base64Strategy: \"contentEncoding:base64\",\n  nameStrategy: \"ref\"\n};\nvar getDefaultOptions = (options) => typeof options === \"string\" ? {\n  ...defaultOptions,\n  name: options\n} : {\n  ...defaultOptions,\n  ...options\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nimport { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/any.ts\nfunction parseAnyDef() {\n  return {};\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/array.ts\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\nfunction parseArrayDef(def, refs) {\n  var _a2, _b2, _c;\n  const res = {\n    type: \"array\"\n  };\n  if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {\n    res.items = parseDef(def.type._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, \"items\"]\n    });\n  }\n  if (def.minLength) {\n    res.minItems = def.minLength.value;\n  }\n  if (def.maxLength) {\n    res.maxItems = def.maxLength.value;\n  }\n  if (def.exactLength) {\n    res.minItems = def.exactLength.value;\n    res.maxItems = def.exactLength.value;\n  }\n  return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts\nfunction parseBigintDef(def) {\n  const res = {\n    type: \"integer\",\n    format: \"int64\"\n  };\n  if (!def.checks) return res;\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case \"min\":\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case \"max\":\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n        break;\n      case \"multipleOf\":\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts\nfunction parseBooleanDef() {\n  return { type: \"boolean\" };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/branded.ts\nfunction parseBrandedDef(_def, refs) {\n  return parseDef(_def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/catch.ts\nvar parseCatchDef = (def, refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/date.ts\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n  const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;\n  if (Array.isArray(strategy)) {\n    return {\n      anyOf: strategy.map((item) => parseDateDef(def, refs, item))\n    };\n  }\n  switch (strategy) {\n    case \"string\":\n    case \"format:date-time\":\n      return {\n        type: \"string\",\n        format: \"date-time\"\n      };\n    case \"format:date\":\n      return {\n        type: \"string\",\n        format: \"date\"\n      };\n    case \"integer\":\n      return integerDateParser(def);\n  }\n}\nvar integerDateParser = (def) => {\n  const res = {\n    type: \"integer\",\n    format: \"unix-time\"\n  };\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case \"min\":\n        res.minimum = check.value;\n        break;\n      case \"max\":\n        res.maximum = check.value;\n        break;\n    }\n  }\n  return res;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/default.ts\nfunction parseDefaultDef(_def, refs) {\n  return {\n    ...parseDef(_def.innerType._def, refs),\n    default: _def.defaultValue()\n  };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/effects.ts\nfunction parseEffectsDef(_def, refs) {\n  return refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/enum.ts\nfunction parseEnumDef(def) {\n  return {\n    type: \"string\",\n    enum: Array.from(def.values)\n  };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts\nvar isJsonSchema7AllOfType = (type) => {\n  if (\"type\" in type && type.type === \"string\") return false;\n  return \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n  const allOf = [\n    parseDef(def.left._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n    }),\n    parseDef(def.right._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, \"allOf\", \"1\"]\n    })\n  ].filter((x) => !!x);\n  const mergedAllOf = [];\n  allOf.forEach((schema) => {\n    if (isJsonSchema7AllOfType(schema)) {\n      mergedAllOf.push(...schema.allOf);\n    } else {\n      let nestedSchema = schema;\n      if (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n        const { additionalProperties: _additionalProperties, ...rest } = schema;\n        nestedSchema = rest;\n      }\n      mergedAllOf.push(nestedSchema);\n    }\n  });\n  return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/literal.ts\nfunction parseLiteralDef(def) {\n  const parsedType = typeof def.value;\n  if (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") {\n    return {\n      type: Array.isArray(def.value) ? \"array\" : \"object\"\n    };\n  }\n  return {\n    type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n    const: def.value\n  };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nimport {\n  ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2\n} from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/string.ts\nvar emojiRegex = void 0;\nvar zodPatterns = {\n  /**\n   * `c` was changed to `[cC]` to replicate /i flag\n   */\n  cuid: /^[cC][^\\s-]{8,}$/,\n  cuid2: /^[0-9a-z]+$/,\n  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n  /**\n   * `a-z` was added to replicate /i flag\n   */\n  email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n  /**\n   * Constructed a valid Unicode RegExp\n   *\n   * Lazily instantiate since this type of regex isn't supported\n   * in all envs (e.g. React Native).\n   *\n   * See:\n   * https://github.com/colinhacks/zod/issues/2433\n   * Fix in Zod:\n   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n   */\n  emoji: () => {\n    if (emojiRegex === void 0) {\n      emojiRegex = RegExp(\n        \"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\",\n        \"u\"\n      );\n    }\n    return emojiRegex;\n  },\n  /**\n   * Unused\n   */\n  uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n  /**\n   * Unused\n   */\n  ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n  ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n  /**\n   * Unused\n   */\n  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n  ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n  base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n  nanoid: /^[a-zA-Z0-9_-]{21}$/,\n  jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n  const res = {\n    type: \"string\"\n  };\n  if (def.checks) {\n    for (const check of def.checks) {\n      switch (check.kind) {\n        case \"min\":\n          res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n          break;\n        case \"max\":\n          res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n          break;\n        case \"email\":\n          switch (refs.emailStrategy) {\n            case \"format:email\":\n              addFormat(res, \"email\", check.message, refs);\n              break;\n            case \"format:idn-email\":\n              addFormat(res, \"idn-email\", check.message, refs);\n              break;\n            case \"pattern:zod\":\n              addPattern(res, zodPatterns.email, check.message, refs);\n              break;\n          }\n          break;\n        case \"url\":\n          addFormat(res, \"uri\", check.message, refs);\n          break;\n        case \"uuid\":\n          addFormat(res, \"uuid\", check.message, refs);\n          break;\n        case \"regex\":\n          addPattern(res, check.regex, check.message, refs);\n          break;\n        case \"cuid\":\n          addPattern(res, zodPatterns.cuid, check.message, refs);\n          break;\n        case \"cuid2\":\n          addPattern(res, zodPatterns.cuid2, check.message, refs);\n          break;\n        case \"startsWith\":\n          addPattern(\n            res,\n            RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n            check.message,\n            refs\n          );\n          break;\n        case \"endsWith\":\n          addPattern(\n            res,\n            RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n            check.message,\n            refs\n          );\n          break;\n        case \"datetime\":\n          addFormat(res, \"date-time\", check.message, refs);\n          break;\n        case \"date\":\n          addFormat(res, \"date\", check.message, refs);\n          break;\n        case \"time\":\n          addFormat(res, \"time\", check.message, refs);\n          break;\n        case \"duration\":\n          addFormat(res, \"duration\", check.message, refs);\n          break;\n        case \"length\":\n          res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n          res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n          break;\n        case \"includes\": {\n          addPattern(\n            res,\n            RegExp(escapeLiteralCheckValue(check.value, refs)),\n            check.message,\n            refs\n          );\n          break;\n        }\n        case \"ip\": {\n          if (check.version !== \"v6\") {\n            addFormat(res, \"ipv4\", check.message, refs);\n          }\n          if (check.version !== \"v4\") {\n            addFormat(res, \"ipv6\", check.message, refs);\n          }\n          break;\n        }\n        case \"base64url\":\n          addPattern(res, zodPatterns.base64url, check.message, refs);\n          break;\n        case \"jwt\":\n          addPattern(res, zodPatterns.jwt, check.message, refs);\n          break;\n        case \"cidr\": {\n          if (check.version !== \"v6\") {\n            addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n          }\n          if (check.version !== \"v4\") {\n            addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n          }\n          break;\n        }\n        case \"emoji\":\n          addPattern(res, zodPatterns.emoji(), check.message, refs);\n          break;\n        case \"ulid\": {\n          addPattern(res, zodPatterns.ulid, check.message, refs);\n          break;\n        }\n        case \"base64\": {\n          switch (refs.base64Strategy) {\n            case \"format:binary\": {\n              addFormat(res, \"binary\", check.message, refs);\n              break;\n            }\n            case \"contentEncoding:base64\": {\n              res.contentEncoding = \"base64\";\n              break;\n            }\n            case \"pattern:zod\": {\n              addPattern(res, zodPatterns.base64, check.message, refs);\n              break;\n            }\n          }\n          break;\n        }\n        case \"nanoid\": {\n          addPattern(res, zodPatterns.nanoid, check.message, refs);\n        }\n        case \"toLowerCase\":\n        case \"toUpperCase\":\n        case \"trim\":\n          break;\n        default:\n          /* @__PURE__ */ ((_) => {\n          })(check);\n      }\n    }\n  }\n  return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n  return refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nvar ALPHA_NUMERIC = new Set(\n  \"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\"\n);\nfunction escapeNonAlphaNumeric(source) {\n  let result = \"\";\n  for (let i = 0; i < source.length; i++) {\n    if (!ALPHA_NUMERIC.has(source[i])) {\n      result += \"\\\\\";\n    }\n    result += source[i];\n  }\n  return result;\n}\nfunction addFormat(schema, value, message, refs) {\n  var _a2;\n  if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {\n    if (!schema.anyOf) {\n      schema.anyOf = [];\n    }\n    if (schema.format) {\n      schema.anyOf.push({\n        format: schema.format\n      });\n      delete schema.format;\n    }\n    schema.anyOf.push({\n      format: value,\n      ...message && refs.errorMessages && { errorMessage: { format: message } }\n    });\n  } else {\n    schema.format = value;\n  }\n}\nfunction addPattern(schema, regex, message, refs) {\n  var _a2;\n  if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {\n    if (!schema.allOf) {\n      schema.allOf = [];\n    }\n    if (schema.pattern) {\n      schema.allOf.push({\n        pattern: schema.pattern\n      });\n      delete schema.pattern;\n    }\n    schema.allOf.push({\n      pattern: stringifyRegExpWithFlags(regex, refs),\n      ...message && refs.errorMessages && { errorMessage: { pattern: message } }\n    });\n  } else {\n    schema.pattern = stringifyRegExpWithFlags(regex, refs);\n  }\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n  var _a2;\n  if (!refs.applyRegexFlags || !regex.flags) {\n    return regex.source;\n  }\n  const flags = {\n    i: regex.flags.includes(\"i\"),\n    // Case-insensitive\n    m: regex.flags.includes(\"m\"),\n    // `^` and `$` matches adjacent to newline characters\n    s: regex.flags.includes(\"s\")\n    // `.` matches newlines\n  };\n  const source = flags.i ? regex.source.toLowerCase() : regex.source;\n  let pattern = \"\";\n  let isEscaped = false;\n  let inCharGroup = false;\n  let inCharRange = false;\n  for (let i = 0; i < source.length; i++) {\n    if (isEscaped) {\n      pattern += source[i];\n      isEscaped = false;\n      continue;\n    }\n    if (flags.i) {\n      if (inCharGroup) {\n        if (source[i].match(/[a-z]/)) {\n          if (inCharRange) {\n            pattern += source[i];\n            pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n            inCharRange = false;\n          } else if (source[i + 1] === \"-\" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {\n            pattern += source[i];\n            inCharRange = true;\n          } else {\n            pattern += `${source[i]}${source[i].toUpperCase()}`;\n          }\n          continue;\n        }\n      } else if (source[i].match(/[a-z]/)) {\n        pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n        continue;\n      }\n    }\n    if (flags.m) {\n      if (source[i] === \"^\") {\n        pattern += `(^|(?<=[\\r\n]))`;\n        continue;\n      } else if (source[i] === \"$\") {\n        pattern += `($|(?=[\\r\n]))`;\n        continue;\n      }\n    }\n    if (flags.s && source[i] === \".\") {\n      pattern += inCharGroup ? `${source[i]}\\r\n` : `[${source[i]}\\r\n]`;\n      continue;\n    }\n    pattern += source[i];\n    if (source[i] === \"\\\\\") {\n      isEscaped = true;\n    } else if (inCharGroup && source[i] === \"]\") {\n      inCharGroup = false;\n    } else if (!inCharGroup && source[i] === \"[\") {\n      inCharGroup = true;\n    }\n  }\n  try {\n    new RegExp(pattern);\n  } catch (e) {\n    console.warn(\n      `Could not convert regex pattern at ${refs.currentPath.join(\n        \"/\"\n      )} to a flag-independent form! Falling back to the flag-ignorant source`\n    );\n    return regex.source;\n  }\n  return pattern;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nfunction parseRecordDef(def, refs) {\n  var _a2, _b2, _c, _d, _e, _f;\n  const schema = {\n    type: \"object\",\n    additionalProperties: (_a2 = parseDef(def.valueType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, \"additionalProperties\"]\n    })) != null ? _a2 : refs.allowedAdditionalProperties\n  };\n  if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {\n    const { type: _type, ...keyType } = parseStringDef(def.keyType._def, refs);\n    return {\n      ...schema,\n      propertyNames: keyType\n    };\n  } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {\n    return {\n      ...schema,\n      propertyNames: {\n        enum: def.keyType._def.values\n      }\n    };\n  } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {\n    const { type: _type, ...keyType } = parseBrandedDef(\n      def.keyType._def,\n      refs\n    );\n    return {\n      ...schema,\n      propertyNames: keyType\n    };\n  }\n  return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/map.ts\nfunction parseMapDef(def, refs) {\n  if (refs.mapStrategy === \"record\") {\n    return parseRecordDef(def, refs);\n  }\n  const keys = parseDef(def.keyType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"]\n  }) || parseAnyDef();\n  const values = parseDef(def.valueType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"]\n  }) || parseAnyDef();\n  return {\n    type: \"array\",\n    maxItems: 125,\n    items: {\n      type: \"array\",\n      items: [keys, values],\n      minItems: 2,\n      maxItems: 2\n    }\n  };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts\nfunction parseNativeEnumDef(def) {\n  const object = def.values;\n  const actualKeys = Object.keys(def.values).filter((key) => {\n    return typeof object[object[key]] !== \"number\";\n  });\n  const actualValues = actualKeys.map((key) => object[key]);\n  const parsedTypes = Array.from(\n    new Set(actualValues.map((values) => typeof values))\n  );\n  return {\n    type: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n    enum: actualValues\n  };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/never.ts\nfunction parseNeverDef() {\n  return { not: parseAnyDef() };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/null.ts\nfunction parseNullDef() {\n  return {\n    type: \"null\"\n  };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/union.ts\nvar primitiveMappings = {\n  ZodString: \"string\",\n  ZodNumber: \"number\",\n  ZodBigInt: \"integer\",\n  ZodBoolean: \"boolean\",\n  ZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n  if (options.every(\n    (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)\n  )) {\n    const types = options.reduce((types2, x) => {\n      const type = primitiveMappings[x._def.typeName];\n      return type && !types2.includes(type) ? [...types2, type] : types2;\n    }, []);\n    return {\n      type: types.length > 1 ? types : types[0]\n    };\n  } else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n    const types = options.reduce(\n      (acc, x) => {\n        const type = typeof x._def.value;\n        switch (type) {\n          case \"string\":\n          case \"number\":\n          case \"boolean\":\n            return [...acc, type];\n          case \"bigint\":\n            return [...acc, \"integer\"];\n          case \"object\":\n            if (x._def.value === null) return [...acc, \"null\"];\n          case \"symbol\":\n          case \"undefined\":\n          case \"function\":\n          default:\n            return acc;\n        }\n      },\n      []\n    );\n    if (types.length === options.length) {\n      const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n      return {\n        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n        enum: options.reduce(\n          (acc, x) => {\n            return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n          },\n          []\n        )\n      };\n    }\n  } else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n    return {\n      type: \"string\",\n      enum: options.reduce(\n        (acc, x) => [\n          ...acc,\n          ...x._def.values.filter((x2) => !acc.includes(x2))\n        ],\n        []\n      )\n    };\n  }\n  return asAnyOf(def, refs);\n}\nvar asAnyOf = (def, refs) => {\n  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(\n    (x, i) => parseDef(x._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, \"anyOf\", `${i}`]\n    })\n  ).filter(\n    (x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0)\n  );\n  return anyOf.length ? { anyOf } : void 0;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts\nfunction parseNullableDef(def, refs) {\n  if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(\n    def.innerType._def.typeName\n  ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n    return {\n      type: [\n        primitiveMappings[def.innerType._def.typeName],\n        \"null\"\n      ]\n    };\n  }\n  const base = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, \"anyOf\", \"0\"]\n  });\n  return base && { anyOf: [base, { type: \"null\" }] };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/number.ts\nfunction parseNumberDef(def) {\n  const res = {\n    type: \"number\"\n  };\n  if (!def.checks) return res;\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case \"int\":\n        res.type = \"integer\";\n        break;\n      case \"min\":\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case \"max\":\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n        break;\n      case \"multipleOf\":\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/object.ts\nfunction parseObjectDef(def, refs) {\n  const result = {\n    type: \"object\",\n    properties: {}\n  };\n  const required = [];\n  const shape = def.shape();\n  for (const propName in shape) {\n    let propDef = shape[propName];\n    if (propDef === void 0 || propDef._def === void 0) {\n      continue;\n    }\n    const propOptional = safeIsOptional(propDef);\n    const parsedDef = parseDef(propDef._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, \"properties\", propName],\n      propertyPath: [...refs.currentPath, \"properties\", propName]\n    });\n    if (parsedDef === void 0) {\n      continue;\n    }\n    result.properties[propName] = parsedDef;\n    if (!propOptional) {\n      required.push(propName);\n    }\n  }\n  if (required.length) {\n    result.required = required;\n  }\n  const additionalProperties = decideAdditionalProperties(def, refs);\n  if (additionalProperties !== void 0) {\n    result.additionalProperties = additionalProperties;\n  }\n  return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n  if (def.catchall._def.typeName !== \"ZodNever\") {\n    return parseDef(def.catchall._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, \"additionalProperties\"]\n    });\n  }\n  switch (def.unknownKeys) {\n    case \"passthrough\":\n      return refs.allowedAdditionalProperties;\n    case \"strict\":\n      return refs.rejectedAdditionalProperties;\n    case \"strip\":\n      return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n  }\n}\nfunction safeIsOptional(schema) {\n  try {\n    return schema.isOptional();\n  } catch (e) {\n    return true;\n  }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/optional.ts\nvar parseOptionalDef = (def, refs) => {\n  var _a2;\n  if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) {\n    return parseDef(def.innerType._def, refs);\n  }\n  const innerSchema = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, \"anyOf\", \"1\"]\n  });\n  return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts\nvar parsePipelineDef = (def, refs) => {\n  if (refs.pipeStrategy === \"input\") {\n    return parseDef(def.in._def, refs);\n  } else if (refs.pipeStrategy === \"output\") {\n    return parseDef(def.out._def, refs);\n  }\n  const inputSchema = parseDef(def.in._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n  });\n  const outputSchema = parseDef(def.out._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, \"allOf\", inputSchema ? \"1\" : \"0\"]\n  });\n  return {\n    allOf: [inputSchema, outputSchema].filter(\n      (schema) => schema !== void 0\n    )\n  };\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/promise.ts\nfunction parsePromiseDef(def, refs) {\n  return parseDef(def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/set.ts\nfunction parseSetDef(def, refs) {\n  const items = parseDef(def.valueType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, \"items\"]\n  });\n  const schema = {\n    type: \"array\",\n    uniqueItems: true,\n    items\n  };\n  if (def.minSize) {\n    schema.minItems = def.minSize.value;\n  }\n  if (def.maxSize) {\n    schema.maxItems = def.maxSize.value;\n  }\n  return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts\nfunction parseTupleDef(def, refs) {\n  if (def.rest) {\n    return {\n      type: \"array\",\n      minItems: def.items.length,\n      items: def.items.map(\n        (x, i) => parseDef(x._def, {\n          ...refs,\n          currentPath: [...refs.currentPath, \"items\", `${i}`]\n        })\n      ).reduce(\n        (acc, x) => x === void 0 ? acc : [...acc, x],\n        []\n      ),\n      additionalItems: parseDef(def.rest._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, \"additionalItems\"]\n      })\n    };\n  } else {\n    return {\n      type: \"array\",\n      minItems: def.items.length,\n      maxItems: def.items.length,\n      items: def.items.map(\n        (x, i) => parseDef(x._def, {\n          ...refs,\n          currentPath: [...refs.currentPath, \"items\", `${i}`]\n        })\n      ).reduce(\n        (acc, x) => x === void 0 ? acc : [...acc, x],\n        []\n      )\n    };\n  }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts\nfunction parseUndefinedDef() {\n  return {\n    not: parseAnyDef()\n  };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts\nfunction parseUnknownDef() {\n  return parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts\nvar parseReadonlyDef = (def, refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nvar selectParser = (def, typeName, refs) => {\n  switch (typeName) {\n    case ZodFirstPartyTypeKind3.ZodString:\n      return parseStringDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodNumber:\n      return parseNumberDef(def);\n    case ZodFirstPartyTypeKind3.ZodObject:\n      return parseObjectDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodBigInt:\n      return parseBigintDef(def);\n    case ZodFirstPartyTypeKind3.ZodBoolean:\n      return parseBooleanDef();\n    case ZodFirstPartyTypeKind3.ZodDate:\n      return parseDateDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodUndefined:\n      return parseUndefinedDef();\n    case ZodFirstPartyTypeKind3.ZodNull:\n      return parseNullDef();\n    case ZodFirstPartyTypeKind3.ZodArray:\n      return parseArrayDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodUnion:\n    case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:\n      return parseUnionDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodIntersection:\n      return parseIntersectionDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodTuple:\n      return parseTupleDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodRecord:\n      return parseRecordDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodLiteral:\n      return parseLiteralDef(def);\n    case ZodFirstPartyTypeKind3.ZodEnum:\n      return parseEnumDef(def);\n    case ZodFirstPartyTypeKind3.ZodNativeEnum:\n      return parseNativeEnumDef(def);\n    case ZodFirstPartyTypeKind3.ZodNullable:\n      return parseNullableDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodOptional:\n      return parseOptionalDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodMap:\n      return parseMapDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodSet:\n      return parseSetDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodLazy:\n      return () => def.getter()._def;\n    case ZodFirstPartyTypeKind3.ZodPromise:\n      return parsePromiseDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodNaN:\n    case ZodFirstPartyTypeKind3.ZodNever:\n      return parseNeverDef();\n    case ZodFirstPartyTypeKind3.ZodEffects:\n      return parseEffectsDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodAny:\n      return parseAnyDef();\n    case ZodFirstPartyTypeKind3.ZodUnknown:\n      return parseUnknownDef();\n    case ZodFirstPartyTypeKind3.ZodDefault:\n      return parseDefaultDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodBranded:\n      return parseBrandedDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodReadonly:\n      return parseReadonlyDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodCatch:\n      return parseCatchDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodPipeline:\n      return parsePipelineDef(def, refs);\n    case ZodFirstPartyTypeKind3.ZodFunction:\n    case ZodFirstPartyTypeKind3.ZodVoid:\n    case ZodFirstPartyTypeKind3.ZodSymbol:\n      return void 0;\n    default:\n      return /* @__PURE__ */ ((_) => void 0)(typeName);\n  }\n};\n\n// src/to-json-schema/zod3-to-json-schema/get-relative-path.ts\nvar getRelativePath = (pathA, pathB) => {\n  let i = 0;\n  for (; i < pathA.length && i < pathB.length; i++) {\n    if (pathA[i] !== pathB[i]) break;\n  }\n  return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n\n// src/to-json-schema/zod3-to-json-schema/parse-def.ts\nfunction parseDef(def, refs, forceResolution = false) {\n  var _a2;\n  const seenItem = refs.seen.get(def);\n  if (refs.override) {\n    const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(\n      refs,\n      def,\n      refs,\n      seenItem,\n      forceResolution\n    );\n    if (overrideResult !== ignoreOverride) {\n      return overrideResult;\n    }\n  }\n  if (seenItem && !forceResolution) {\n    const seenSchema = get$ref(seenItem, refs);\n    if (seenSchema !== void 0) {\n      return seenSchema;\n    }\n  }\n  const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };\n  refs.seen.set(def, newItem);\n  const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n  const jsonSchema2 = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n  if (jsonSchema2) {\n    addMeta(def, refs, jsonSchema2);\n  }\n  if (refs.postProcess) {\n    const postProcessResult = refs.postProcess(jsonSchema2, def, refs);\n    newItem.jsonSchema = jsonSchema2;\n    return postProcessResult;\n  }\n  newItem.jsonSchema = jsonSchema2;\n  return jsonSchema2;\n}\nvar get$ref = (item, refs) => {\n  switch (refs.$refStrategy) {\n    case \"root\":\n      return { $ref: item.path.join(\"/\") };\n    case \"relative\":\n      return { $ref: getRelativePath(refs.currentPath, item.path) };\n    case \"none\":\n    case \"seen\": {\n      if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n        console.warn(\n          `Recursive reference detected at ${refs.currentPath.join(\n            \"/\"\n          )}! Defaulting to any`\n        );\n        return parseAnyDef();\n      }\n      return refs.$refStrategy === \"seen\" ? parseAnyDef() : void 0;\n    }\n  }\n};\nvar addMeta = (def, refs, jsonSchema2) => {\n  if (def.description) {\n    jsonSchema2.description = def.description;\n  }\n  return jsonSchema2;\n};\n\n// src/to-json-schema/zod3-to-json-schema/refs.ts\nvar getRefs = (options) => {\n  const _options = getDefaultOptions(options);\n  const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;\n  return {\n    ..._options,\n    currentPath,\n    propertyPath: void 0,\n    seen: new Map(\n      Object.entries(_options.definitions).map(([name2, def]) => [\n        def._def,\n        {\n          def: def._def,\n          path: [..._options.basePath, _options.definitionPath, name2],\n          // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n          jsonSchema: void 0\n        }\n      ])\n    )\n  };\n};\n\n// src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts\nvar zod3ToJsonSchema = (schema, options) => {\n  var _a2;\n  const refs = getRefs(options);\n  let definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce(\n    (acc, [name3, schema2]) => {\n      var _a3;\n      return {\n        ...acc,\n        [name3]: (_a3 = parseDef(\n          schema2._def,\n          {\n            ...refs,\n            currentPath: [...refs.basePath, refs.definitionPath, name3]\n          },\n          true\n        )) != null ? _a3 : parseAnyDef()\n      };\n    },\n    {}\n  ) : void 0;\n  const name2 = typeof options === \"string\" ? options : (options == null ? void 0 : options.nameStrategy) === \"title\" ? void 0 : options == null ? void 0 : options.name;\n  const main = (_a2 = parseDef(\n    schema._def,\n    name2 === void 0 ? refs : {\n      ...refs,\n      currentPath: [...refs.basePath, refs.definitionPath, name2]\n    },\n    false\n  )) != null ? _a2 : parseAnyDef();\n  const title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n  if (title !== void 0) {\n    main.title = title;\n  }\n  const combined = name2 === void 0 ? definitions ? {\n    ...main,\n    [refs.definitionPath]: definitions\n  } : main : {\n    $ref: [\n      ...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n      refs.definitionPath,\n      name2\n    ].join(\"/\"),\n    [refs.definitionPath]: {\n      ...definitions,\n      [name2]: main\n    }\n  };\n  combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n  return combined;\n};\n\n// src/schema.ts\nvar schemaSymbol = /* @__PURE__ */ Symbol.for(\"vercel.ai.schema\");\nfunction lazySchema(createSchema) {\n  let schema;\n  return () => {\n    if (schema == null) {\n      schema = createSchema();\n    }\n    return schema;\n  };\n}\nfunction jsonSchema(jsonSchema2, {\n  validate\n} = {}) {\n  return {\n    [schemaSymbol]: true,\n    _type: void 0,\n    // should never be used directly\n    get jsonSchema() {\n      if (typeof jsonSchema2 === \"function\") {\n        jsonSchema2 = jsonSchema2();\n      }\n      return jsonSchema2;\n    },\n    validate\n  };\n}\nfunction isSchema(value) {\n  return typeof value === \"object\" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && \"jsonSchema\" in value && \"validate\" in value;\n}\nfunction asSchema(schema) {\n  return schema == null ? jsonSchema({\n    type: \"object\",\n    properties: {},\n    additionalProperties: false\n  }) : isSchema(schema) ? schema : \"~standard\" in schema ? schema[\"~standard\"].vendor === \"zod\" ? zodSchema(schema) : standardSchema(schema) : schema();\n}\nfunction standardSchema(standardSchema2) {\n  return jsonSchema(\n    () => addAdditionalPropertiesToJsonSchema(\n      standardSchema2[\"~standard\"].jsonSchema.input({\n        target: \"draft-07\"\n      })\n    ),\n    {\n      validate: async (value) => {\n        const result = await standardSchema2[\"~standard\"].validate(value);\n        return \"value\" in result ? { success: true, value: result.value } : {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause: result.issues\n          })\n        };\n      }\n    }\n  );\n}\nfunction zod3Schema(zodSchema2, options) {\n  var _a2;\n  const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () => zod3ToJsonSchema(zodSchema2, {\n      $refStrategy: useReferences ? \"root\" : \"none\"\n    }),\n    {\n      validate: async (value) => {\n        const result = await zodSchema2.safeParseAsync(value);\n        return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n      }\n    }\n  );\n}\nfunction zod4Schema(zodSchema2, options) {\n  var _a2;\n  const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () => addAdditionalPropertiesToJsonSchema(\n      z4.toJSONSchema(zodSchema2, {\n        target: \"draft-7\",\n        io: \"input\",\n        reused: useReferences ? \"ref\" : \"inline\"\n      })\n    ),\n    {\n      validate: async (value) => {\n        const result = await z4.safeParseAsync(zodSchema2, value);\n        return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n      }\n    }\n  );\n}\nfunction isZod4Schema(zodSchema2) {\n  return \"_zod\" in zodSchema2;\n}\nfunction zodSchema(zodSchema2, options) {\n  if (isZod4Schema(zodSchema2)) {\n    return zod4Schema(zodSchema2, options);\n  } else {\n    return zod3Schema(zodSchema2, options);\n  }\n}\n\n// src/validate-types.ts\nasync function validateTypes({\n  value,\n  schema,\n  context\n}) {\n  const result = await safeValidateTypes({ value, schema, context });\n  if (!result.success) {\n    throw TypeValidationError2.wrap({ value, cause: result.error, context });\n  }\n  return result.value;\n}\nasync function safeValidateTypes({\n  value,\n  schema,\n  context\n}) {\n  const actualSchema = asSchema(schema);\n  try {\n    if (actualSchema.validate == null) {\n      return { success: true, value, rawValue: value };\n    }\n    const result = await actualSchema.validate(value);\n    if (result.success) {\n      return { success: true, value: result.value, rawValue: value };\n    }\n    return {\n      success: false,\n      error: TypeValidationError2.wrap({ value, cause: result.error, context }),\n      rawValue: value\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: TypeValidationError2.wrap({ value, cause: error, context }),\n      rawValue: value\n    };\n  }\n}\n\n// src/parse-json.ts\nasync function parseJSON({\n  text,\n  schema\n}) {\n  try {\n    const value = secureJsonParse(text);\n    if (schema == null) {\n      return value;\n    }\n    return await validateTypes({ value, schema });\n  } catch (error) {\n    if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {\n      throw error;\n    }\n    throw new JSONParseError({ text, cause: error });\n  }\n}\nasync function safeParseJSON({\n  text,\n  schema\n}) {\n  try {\n    const value = secureJsonParse(text);\n    if (schema == null) {\n      return { success: true, value, rawValue: value };\n    }\n    return await safeValidateTypes({ value, schema });\n  } catch (error) {\n    return {\n      success: false,\n      error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),\n      rawValue: void 0\n    };\n  }\n}\nfunction isParsableJson(input) {\n  try {\n    secureJsonParse(input);\n    return true;\n  } catch (e) {\n    return false;\n  }\n}\n\n// src/parse-json-event-stream.ts\nimport {\n  EventSourceParserStream\n} from \"eventsource-parser/stream\";\nfunction parseJsonEventStream({\n  stream,\n  schema\n}) {\n  return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(\n    new TransformStream({\n      async transform({ data }, controller) {\n        if (data === \"[DONE]\") {\n          return;\n        }\n        controller.enqueue(await safeParseJSON({ text: data, schema }));\n      }\n    })\n  );\n}\n\n// src/parse-provider-options.ts\nimport { InvalidArgumentError as InvalidArgumentError2 } from \"@ai-sdk/provider\";\nasync function parseProviderOptions({\n  provider,\n  providerOptions,\n  schema\n}) {\n  if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {\n    return void 0;\n  }\n  const parsedProviderOptions = await safeValidateTypes({\n    value: providerOptions[provider],\n    schema\n  });\n  if (!parsedProviderOptions.success) {\n    throw new InvalidArgumentError2({\n      argument: \"providerOptions\",\n      message: `invalid ${provider} provider options`,\n      cause: parsedProviderOptions.error\n    });\n  }\n  return parsedProviderOptions.value;\n}\n\n// src/post-to-api.ts\nimport { APICallError as APICallError3 } from \"@ai-sdk/provider\";\nvar getOriginalFetch2 = () => globalThis.fetch;\nvar postJsonToApi = async ({\n  url,\n  headers,\n  body,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch: fetch2\n}) => await postToApi({\n  url,\n  headers: {\n    \"Content-Type\": \"application/json\",\n    ...headers\n  },\n  body: {\n    content: JSON.stringify(body),\n    values: body\n  },\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch: fetch2\n});\nvar postFormDataToApi = async ({\n  url,\n  headers,\n  formData,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch: fetch2\n}) => await postToApi({\n  url,\n  headers,\n  body: {\n    content: formData,\n    values: Object.fromEntries(formData.entries())\n  },\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch: fetch2\n});\nvar postToApi = async ({\n  url,\n  headers = {},\n  body,\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch: fetch2 = getOriginalFetch2()\n}) => {\n  try {\n    const response = await fetch2(url, {\n      method: \"POST\",\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent()\n      ),\n      body: body.content,\n      signal: abortSignal\n    });\n    const responseHeaders = extractResponseHeaders(response);\n    if (!response.ok) {\n      let errorInformation;\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: body.values\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError3.isInstance(error)) {\n          throw error;\n        }\n        throw new APICallError3({\n          message: \"Failed to process error response\",\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: body.values\n        });\n      }\n      throw errorInformation.value;\n    }\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: body.values\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError3.isInstance(error)) {\n          throw error;\n        }\n      }\n      throw new APICallError3({\n        message: \"Failed to process successful response\",\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: body.values\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: body.values });\n  }\n};\n\n// src/types/tool.ts\nfunction tool(tool2) {\n  return tool2;\n}\nfunction dynamicTool(tool2) {\n  return { ...tool2, type: \"dynamic\" };\n}\n\n// src/provider-defined-tool-factory.ts\nfunction createProviderDefinedToolFactory({\n  id,\n  inputSchema\n}) {\n  return ({\n    execute,\n    outputSchema,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }) => tool({\n    type: \"provider\",\n    isProviderExecuted: false,\n    id,\n    args,\n    inputSchema,\n    outputSchema,\n    execute,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable\n  });\n}\nfunction createProviderDefinedToolFactoryWithOutputSchema({\n  id,\n  inputSchema,\n  outputSchema\n}) {\n  return ({\n    execute,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }) => tool({\n    type: \"provider\",\n    isProviderExecuted: false,\n    id,\n    args,\n    inputSchema,\n    outputSchema,\n    execute,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable\n  });\n}\n\n// src/provider-executed-tool-factory.ts\nfunction createProviderExecutedToolFactory({\n  id,\n  inputSchema,\n  outputSchema,\n  supportsDeferredResults\n}) {\n  return ({\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }) => tool({\n    type: \"provider\",\n    isProviderExecuted: true,\n    id,\n    args,\n    inputSchema,\n    outputSchema,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    supportsDeferredResults\n  });\n}\n\n// src/remove-undefined-entries.ts\nfunction removeUndefinedEntries(record) {\n  return Object.fromEntries(\n    Object.entries(record).filter(([_key, value]) => value != null)\n  );\n}\n\n// src/resolve.ts\nasync function resolve(value) {\n  if (typeof value === \"function\") {\n    value = value();\n  }\n  return Promise.resolve(value);\n}\n\n// src/resolve-full-media-type.ts\nimport {\n  UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nfunction resolveFullMediaType({\n  part\n}) {\n  if (isFullMediaType(part.mediaType)) {\n    return part.mediaType;\n  }\n  if (part.data.type === \"data\") {\n    const detected = detectMediaType({\n      data: part.data.data,\n      topLevelType: getTopLevelMediaType(part.mediaType)\n    });\n    if (detected) {\n      return detected;\n    }\n    throw new UnsupportedFunctionalityError({\n      functionality: `file of media type \"${part.mediaType}\" must specify subtype since it could not be auto-detected`\n    });\n  }\n  throw new UnsupportedFunctionalityError({\n    functionality: `file of media type \"${part.mediaType}\" must specify subtype since it is not passed as inline bytes`\n  });\n}\n\n// src/resolve-provider-reference.ts\nimport {\n  NoSuchProviderReferenceError\n} from \"@ai-sdk/provider\";\nfunction resolveProviderReference({\n  reference,\n  provider\n}) {\n  const id = reference[provider];\n  if (id != null) {\n    return id;\n  }\n  throw new NoSuchProviderReferenceError({\n    provider,\n    reference\n  });\n}\n\n// src/response-handler.ts\nimport { APICallError as APICallError4, EmptyResponseBodyError } from \"@ai-sdk/provider\";\nvar textDecoder = new TextDecoder();\nasync function readResponseBodyAsText({\n  response,\n  url\n}) {\n  return textDecoder.decode(\n    await readResponseWithSizeLimit({\n      response,\n      url\n    })\n  );\n}\nvar createJsonErrorResponseHandler = ({\n  errorSchema,\n  errorToMessage,\n  isRetryable\n}) => async ({ response, url, requestBodyValues }) => {\n  const responseBody = await readResponseBodyAsText({ response, url });\n  const responseHeaders = extractResponseHeaders(response);\n  if (responseBody.trim() === \"\") {\n    return {\n      responseHeaders,\n      value: new APICallError4({\n        message: response.statusText,\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n        isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n      })\n    };\n  }\n  try {\n    const parsedError = await parseJSON({\n      text: responseBody,\n      schema: errorSchema\n    });\n    return {\n      responseHeaders,\n      value: new APICallError4({\n        message: errorToMessage(parsedError),\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n        data: parsedError,\n        isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)\n      })\n    };\n  } catch (e) {\n    return {\n      responseHeaders,\n      value: new APICallError4({\n        message: response.statusText,\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n        isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n      })\n    };\n  }\n};\nvar createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {\n  const responseHeaders = extractResponseHeaders(response);\n  if (response.body == null) {\n    throw new EmptyResponseBodyError({});\n  }\n  return {\n    responseHeaders,\n    value: parseJsonEventStream({\n      stream: response.body,\n      schema: chunkSchema\n    })\n  };\n};\nvar createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {\n  const responseBody = await readResponseBodyAsText({ response, url });\n  const parsedResult = await safeParseJSON({\n    text: responseBody,\n    schema: responseSchema\n  });\n  const responseHeaders = extractResponseHeaders(response);\n  if (!parsedResult.success) {\n    throw new APICallError4({\n      message: \"Invalid JSON response\",\n      cause: parsedResult.error,\n      statusCode: response.status,\n      responseHeaders,\n      responseBody,\n      url,\n      requestBodyValues\n    });\n  }\n  return {\n    responseHeaders,\n    value: parsedResult.value,\n    rawValue: parsedResult.rawValue\n  };\n};\nvar createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n  const responseHeaders = extractResponseHeaders(response);\n  if (!response.body) {\n    throw new APICallError4({\n      message: \"Response body is empty\",\n      url,\n      requestBodyValues,\n      statusCode: response.status,\n      responseHeaders,\n      responseBody: void 0\n    });\n  }\n  try {\n    const buffer = await response.arrayBuffer();\n    return {\n      responseHeaders,\n      value: new Uint8Array(buffer)\n    };\n  } catch (error) {\n    throw new APICallError4({\n      message: \"Failed to read response as array buffer\",\n      url,\n      requestBodyValues,\n      statusCode: response.status,\n      responseHeaders,\n      responseBody: void 0,\n      cause: error\n    });\n  }\n};\nvar createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n  const responseHeaders = extractResponseHeaders(response);\n  const responseBody = await readResponseBodyAsText({ response, url });\n  return {\n    responseHeaders,\n    value: new APICallError4({\n      message: response.statusText,\n      url,\n      requestBodyValues,\n      statusCode: response.status,\n      responseHeaders,\n      responseBody\n    })\n  };\n};\n\n// src/is-json-serializable.ts\nfunction isJSONSerializable(value) {\n  if (value === null || value === void 0) return true;\n  const type = typeof value;\n  if (type === \"string\" || type === \"number\" || type === \"boolean\") return true;\n  if (type === \"function\" || type === \"symbol\" || type === \"bigint\")\n    return false;\n  if (Array.isArray(value)) {\n    return value.every(isJSONSerializable);\n  }\n  if (Object.getPrototypeOf(value) === Object.prototype) {\n    return Object.values(value).every(\n      isJSONSerializable\n    );\n  }\n  return false;\n}\n\n// src/serialize-model-options.ts\nfunction serializeModelOptions(options) {\n  const serializableConfig = {};\n  for (const [key, value] of Object.entries(options.config)) {\n    if (key === \"headers\") {\n      const resolvedHeaders = resolveSync(value);\n      if (isJSONSerializable(resolvedHeaders)) {\n        serializableConfig[key] = resolvedHeaders;\n      }\n    } else if (isJSONSerializable(value)) {\n      serializableConfig[key] = value;\n    }\n  }\n  return { modelId: options.modelId, config: serializableConfig };\n}\nfunction resolveSync(value) {\n  let next = value;\n  if (typeof value === \"function\") {\n    next = value();\n  }\n  if (next instanceof Promise) {\n    throw new Error(\"Promise returned from resolveSync\");\n  }\n  return next;\n}\n\n// src/streaming-tool-call-tracker.ts\nimport {\n  InvalidResponseDataError\n} from \"@ai-sdk/provider\";\nvar StreamingToolCallTracker = class {\n  constructor(controller, options = {}) {\n    this.toolCalls = [];\n    var _a2, _b2;\n    this.controller = controller;\n    this._generateId = (_a2 = options.generateId) != null ? _a2 : generateId;\n    this.typeValidation = (_b2 = options.typeValidation) != null ? _b2 : \"none\";\n    this.extractMetadata = options.extractMetadata;\n    this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;\n  }\n  /**\n   * Process a tool call delta from a streaming response chunk.\n   * Emits tool-input-start, tool-input-delta, tool-input-end, and tool-call\n   * events as appropriate.\n   */\n  processDelta(toolCallDelta) {\n    var _a2;\n    const index = (_a2 = toolCallDelta.index) != null ? _a2 : this.toolCalls.length;\n    if (this.toolCalls[index] == null) {\n      this.processNewToolCall(index, toolCallDelta);\n    } else {\n      this.processExistingToolCall(index, toolCallDelta);\n    }\n  }\n  /**\n   * Finalize any unfinished tool calls. Should be called during the stream's\n   * flush handler to ensure all tool calls are properly completed.\n   */\n  flush() {\n    for (const toolCall of this.toolCalls) {\n      if (!toolCall.hasFinished) {\n        this.finishToolCall(toolCall);\n      }\n    }\n  }\n  processNewToolCall(index, toolCallDelta) {\n    var _a2, _b2, _c;\n    if (this.typeValidation === \"required\") {\n      if (toolCallDelta.type !== \"function\") {\n        throw new InvalidResponseDataError({\n          data: toolCallDelta,\n          message: `Expected 'function' type.`\n        });\n      }\n    } else if (this.typeValidation === \"if-present\") {\n      if (toolCallDelta.type != null && toolCallDelta.type !== \"function\") {\n        throw new InvalidResponseDataError({\n          data: toolCallDelta,\n          message: `Expected 'function' type.`\n        });\n      }\n    }\n    if (toolCallDelta.id == null) {\n      throw new InvalidResponseDataError({\n        data: toolCallDelta,\n        message: `Expected 'id' to be a string.`\n      });\n    }\n    if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.name) == null) {\n      throw new InvalidResponseDataError({\n        data: toolCallDelta,\n        message: `Expected 'function.name' to be a string.`\n      });\n    }\n    this.controller.enqueue({\n      type: \"tool-input-start\",\n      id: toolCallDelta.id,\n      toolName: toolCallDelta.function.name\n    });\n    const metadata = (_b2 = this.extractMetadata) == null ? void 0 : _b2.call(this, toolCallDelta);\n    this.toolCalls[index] = {\n      id: toolCallDelta.id,\n      type: \"function\",\n      function: {\n        name: toolCallDelta.function.name,\n        arguments: (_c = toolCallDelta.function.arguments) != null ? _c : \"\"\n      },\n      hasFinished: false,\n      metadata\n    };\n    const toolCall = this.toolCalls[index];\n    if (toolCall.function.arguments.length > 0) {\n      this.controller.enqueue({\n        type: \"tool-input-delta\",\n        id: toolCall.id,\n        delta: toolCall.function.arguments\n      });\n    }\n    if (isParsableJson(toolCall.function.arguments)) {\n      this.finishToolCall(toolCall);\n    }\n  }\n  processExistingToolCall(index, toolCallDelta) {\n    var _a2;\n    const toolCall = this.toolCalls[index];\n    if (toolCall.hasFinished) {\n      return;\n    }\n    if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.arguments) != null) {\n      toolCall.function.arguments += toolCallDelta.function.arguments;\n      this.controller.enqueue({\n        type: \"tool-input-delta\",\n        id: toolCall.id,\n        delta: toolCallDelta.function.arguments\n      });\n    }\n    if (isParsableJson(toolCall.function.arguments)) {\n      this.finishToolCall(toolCall);\n    }\n  }\n  finishToolCall(toolCall) {\n    var _a2, _b2;\n    this.controller.enqueue({\n      type: \"tool-input-end\",\n      id: toolCall.id\n    });\n    const providerMetadata = (_a2 = this.buildToolCallProviderMetadata) == null ? void 0 : _a2.call(\n      this,\n      toolCall.metadata\n    );\n    this.controller.enqueue({\n      type: \"tool-call\",\n      toolCallId: (_b2 = toolCall.id) != null ? _b2 : this._generateId(),\n      toolName: toolCall.function.name,\n      input: toolCall.function.arguments,\n      ...providerMetadata ? { providerMetadata } : {}\n    });\n    toolCall.hasFinished = true;\n  }\n};\n\n// src/strip-file-extension.ts\nfunction stripFileExtension(filename) {\n  const firstDotIndex = filename.indexOf(\".\");\n  return firstDotIndex === -1 ? filename : filename.slice(0, firstDotIndex);\n}\n\n// src/without-trailing-slash.ts\nfunction withoutTrailingSlash(url) {\n  return url == null ? void 0 : url.replace(/\\/$/, \"\");\n}\n\n// src/types/executable-tool.ts\nfunction isExecutableTool(tool2) {\n  return tool2 != null && typeof tool2.execute === \"function\";\n}\n\n// src/is-async-iterable.ts\nfunction isAsyncIterable(obj) {\n  return obj != null && typeof obj[Symbol.asyncIterator] === \"function\";\n}\n\n// src/types/execute-tool.ts\nasync function* executeTool({\n  tool: tool2,\n  input,\n  options\n}) {\n  const result = tool2.execute(input, options);\n  if (isAsyncIterable(result)) {\n    let lastOutput;\n    for await (const output of result) {\n      lastOutput = output;\n      yield { type: \"preliminary\", output };\n    }\n    yield { type: \"final\", output: lastOutput };\n  } else {\n    yield { type: \"final\", output: await result };\n  }\n}\n\n// src/index.ts\nimport { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport {\n  EventSourceParserStream as EventSourceParserStream2\n} from \"eventsource-parser/stream\";\nexport {\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n  DelayedPromise,\n  DownloadError,\n  EventSourceParserStream2 as EventSourceParserStream,\n  StreamingToolCallTracker,\n  VERSION,\n  WORKFLOW_DESERIALIZE,\n  WORKFLOW_SERIALIZE,\n  asArray,\n  asSchema,\n  cancelResponseBody,\n  combineHeaders,\n  convertAsyncIteratorToReadableStream,\n  convertBase64ToUint8Array,\n  convertImageModelFileToDataUri,\n  convertInlineFileDataToUint8Array,\n  convertToBase64,\n  convertToFormData,\n  convertUint8ArrayToBase64,\n  createBinaryResponseHandler,\n  createEventSourceResponseHandler,\n  createIdGenerator,\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  createProviderDefinedToolFactory,\n  createProviderDefinedToolFactoryWithOutputSchema,\n  createProviderExecutedToolFactory,\n  createStatusCodeErrorResponseHandler,\n  createToolNameMapping,\n  delay,\n  detectMediaType,\n  downloadBlob,\n  dynamicTool,\n  executeTool,\n  extractLines,\n  extractResponseHeaders,\n  fetchWithValidatedRedirects,\n  filterNullable,\n  generateId,\n  getErrorMessage,\n  getFromApi,\n  getRuntimeEnvironmentUserAgent,\n  getTopLevelMediaType,\n  injectJsonInstructionIntoMessages,\n  isAbortError,\n  isBrowserRuntime,\n  isBuffer,\n  isCustomReasoning,\n  isExecutableTool,\n  isFullMediaType,\n  isNonNullable,\n  isParsableJson,\n  isProviderReference,\n  isSameOrigin,\n  isUrlSupported,\n  jsonSchema,\n  lazySchema,\n  loadApiKey,\n  loadOptionalSetting,\n  loadSetting,\n  mapReasoningToProviderBudget,\n  mapReasoningToProviderEffort,\n  mediaTypeToExtension,\n  normalizeHeaders,\n  parseJSON,\n  parseJsonEventStream,\n  parseProviderOptions,\n  postFormDataToApi,\n  postJsonToApi,\n  postToApi,\n  readResponseWithSizeLimit,\n  removeUndefinedEntries,\n  resolve,\n  resolveFullMediaType,\n  resolveProviderReference,\n  safeParseJSON,\n  safeValidateTypes,\n  serializeModelOptions,\n  stripFileExtension,\n  tool,\n  validateDownloadUrl,\n  validateTypes,\n  withUserAgentSuffix,\n  withoutTrailingSlash,\n  zodSchema\n};\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar get_context_exports = {};\n__export(get_context_exports, {\n  SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,\n  getContext: () => getContext\n});\nmodule.exports = __toCommonJS(get_context_exports);\nconst SYMBOL_FOR_REQ_CONTEXT = Symbol.for(\"@vercel/request-context\");\nfunction getContext() {\n  const fromSymbol = globalThis;\n  return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  SYMBOL_FOR_REQ_CONTEXT,\n  getContext\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_error_exports = {};\n__export(token_error_exports, {\n  VercelOidcTokenError: () => VercelOidcTokenError\n});\nmodule.exports = __toCommonJS(token_error_exports);\nclass VercelOidcTokenError extends Error {\n  constructor(message, cause) {\n    super(message);\n    this.name = \"VercelOidcTokenError\";\n    this.cause = cause;\n  }\n  toString() {\n    if (this.cause) {\n      return `${this.name}: ${this.message}: ${this.cause}`;\n    }\n    return `${this.name}: ${this.message}`;\n  }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  VercelOidcTokenError\n});\n","\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n  // If the importer is in node compatibility mode or this is not an ESM\n  // file that has been converted to a CommonJS file using a Babel-\n  // compatible transform (i.e. \"__esModule\" has not been set), then set\n  // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n  isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n  mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar get_vercel_oidc_token_exports = {};\n__export(get_vercel_oidc_token_exports, {\n  getVercelOidcToken: () => getVercelOidcToken,\n  getVercelOidcTokenSync: () => getVercelOidcTokenSync\n});\nmodule.exports = __toCommonJS(get_vercel_oidc_token_exports);\nvar import_get_context = require(\"./get-context\");\nvar import_token_error = require(\"./token-error\");\nasync function getVercelOidcToken(options) {\n  let token = \"\";\n  let err;\n  try {\n    token = getVercelOidcTokenSync();\n  } catch (error) {\n    err = error;\n  }\n  try {\n    const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([\n      await import(\"./token-util.js\"),\n      await import(\"./token.js\")\n    ]);\n    if (!token || isExpired(getTokenPayload(token), options?.expirationBufferMs)) {\n      await refreshToken(options);\n      token = getVercelOidcTokenSync();\n    }\n  } catch (error) {\n    let message = err instanceof Error ? err.message : \"\";\n    if (error instanceof Error) {\n      message = `${message}\n${error.message}`;\n    }\n    if (message) {\n      throw new import_token_error.VercelOidcTokenError(message);\n    }\n    throw error;\n  }\n  return token;\n}\nfunction getVercelOidcTokenSync() {\n  const token = (0, import_get_context.getContext)().headers?.[\"x-vercel-oidc-token\"] ?? process.env.VERCEL_OIDC_TOKEN;\n  if (!token) {\n    throw new Error(\n      `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`\n    );\n  }\n  return token;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  getVercelOidcToken,\n  getVercelOidcTokenSync\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_errors_exports = {};\n__export(auth_errors_exports, {\n  AccessTokenMissingError: () => AccessTokenMissingError,\n  RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError\n});\nmodule.exports = __toCommonJS(auth_errors_exports);\nclass AccessTokenMissingError extends Error {\n  constructor() {\n    super(\n      \"No authentication found. Please log in with the Vercel CLI (vercel login).\"\n    );\n    this.name = \"AccessTokenMissingError\";\n  }\n}\nclass RefreshAccessTokenFailedError extends Error {\n  constructor(cause) {\n    super(\"Failed to refresh authentication token.\", { cause });\n    this.name = \"RefreshAccessTokenFailedError\";\n  }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  AccessTokenMissingError,\n  RefreshAccessTokenFailedError\n});\n","\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n  // If the importer is in node compatibility mode or this is not an ESM\n  // file that has been converted to a CommonJS file using a Babel-\n  // compatible transform (i.e. \"__esModule\" has not been set), then set\n  // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n  isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n  mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_io_exports = {};\n__export(token_io_exports, {\n  findRootDir: () => findRootDir,\n  getUserDataDir: () => getUserDataDir\n});\nmodule.exports = __toCommonJS(token_io_exports);\nvar import_path = __toESM(require(\"path\"));\nvar import_fs = __toESM(require(\"fs\"));\nvar import_os = __toESM(require(\"os\"));\nvar import_token_error = require(\"./token-error\");\nfunction findRootDir() {\n  try {\n    let dir = process.cwd();\n    while (dir !== import_path.default.dirname(dir)) {\n      const pkgPath = import_path.default.join(dir, \".vercel\");\n      if (import_fs.default.existsSync(pkgPath)) {\n        return dir;\n      }\n      dir = import_path.default.dirname(dir);\n    }\n  } catch (e) {\n    throw new import_token_error.VercelOidcTokenError(\n      \"Token refresh only supported in node server environments\"\n    );\n  }\n  return null;\n}\nfunction getUserDataDir() {\n  if (process.env.XDG_DATA_HOME) {\n    return process.env.XDG_DATA_HOME;\n  }\n  switch (import_os.default.platform()) {\n    case \"darwin\":\n      return import_path.default.join(import_os.default.homedir(), \"Library/Application Support\");\n    case \"linux\":\n      return import_path.default.join(import_os.default.homedir(), \".local/share\");\n    case \"win32\":\n      if (process.env.LOCALAPPDATA) {\n        return process.env.LOCALAPPDATA;\n      }\n      return null;\n    default:\n      return null;\n  }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  findRootDir,\n  getUserDataDir\n});\n","\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n  // If the importer is in node compatibility mode or this is not an ESM\n  // file that has been converted to a CommonJS file using a Babel-\n  // compatible transform (i.e. \"__esModule\" has not been set), then set\n  // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n  isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n  mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_config_exports = {};\n__export(auth_config_exports, {\n  isValidAccessToken: () => isValidAccessToken,\n  readAuthConfig: () => readAuthConfig,\n  writeAuthConfig: () => writeAuthConfig\n});\nmodule.exports = __toCommonJS(auth_config_exports);\nvar fs = __toESM(require(\"fs\"));\nvar path = __toESM(require(\"path\"));\nvar import_token_util = require(\"./token-util\");\nfunction getAuthConfigPath() {\n  const dataDir = (0, import_token_util.getVercelDataDir)();\n  if (!dataDir) {\n    throw new Error(\n      `Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`\n    );\n  }\n  return path.join(dataDir, \"auth.json\");\n}\nfunction readAuthConfig() {\n  try {\n    const authPath = getAuthConfigPath();\n    if (!fs.existsSync(authPath)) {\n      return null;\n    }\n    const content = fs.readFileSync(authPath, \"utf8\");\n    if (!content) {\n      return null;\n    }\n    return JSON.parse(content);\n  } catch (error) {\n    return null;\n  }\n}\nfunction writeAuthConfig(config) {\n  const authPath = getAuthConfigPath();\n  const authDir = path.dirname(authPath);\n  if (!fs.existsSync(authDir)) {\n    fs.mkdirSync(authDir, { mode: 504, recursive: true });\n  }\n  fs.writeFileSync(authPath, JSON.stringify(config, null, 2), { mode: 384 });\n}\nfunction isValidAccessToken(authConfig, expirationBufferMs = 0) {\n  if (!authConfig.token)\n    return false;\n  if (typeof authConfig.expiresAt !== \"number\")\n    return true;\n  const nowInSeconds = Math.floor(Date.now() / 1e3);\n  const bufferInSeconds = expirationBufferMs / 1e3;\n  return authConfig.expiresAt >= nowInSeconds + bufferInSeconds;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  isValidAccessToken,\n  readAuthConfig,\n  writeAuthConfig\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar oauth_exports = {};\n__export(oauth_exports, {\n  processTokenResponse: () => processTokenResponse,\n  refreshTokenRequest: () => refreshTokenRequest\n});\nmodule.exports = __toCommonJS(oauth_exports);\nvar import_os = require(\"os\");\nconst VERCEL_ISSUER = \"https://vercel.com\";\nconst VERCEL_CLI_CLIENT_ID = \"cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp\";\nconst userAgent = `@vercel/oidc node-${process.version} ${(0, import_os.platform)()} (${(0, import_os.arch)()}) ${(0, import_os.hostname)()}`;\nlet _tokenEndpoint = null;\nasync function getTokenEndpoint() {\n  if (_tokenEndpoint) {\n    return _tokenEndpoint;\n  }\n  const discoveryUrl = `${VERCEL_ISSUER}/.well-known/openid-configuration`;\n  const response = await fetch(discoveryUrl, {\n    headers: { \"user-agent\": userAgent }\n  });\n  if (!response.ok) {\n    throw new Error(\"Failed to discover OAuth endpoints\");\n  }\n  const metadata = await response.json();\n  if (!metadata || typeof metadata.token_endpoint !== \"string\") {\n    throw new Error(\"Invalid OAuth discovery response\");\n  }\n  const endpoint = metadata.token_endpoint;\n  _tokenEndpoint = endpoint;\n  return endpoint;\n}\nasync function refreshTokenRequest(options) {\n  const tokenEndpoint = await getTokenEndpoint();\n  return await fetch(tokenEndpoint, {\n    method: \"POST\",\n    headers: {\n      \"Content-Type\": \"application/x-www-form-urlencoded\",\n      \"user-agent\": userAgent\n    },\n    body: new URLSearchParams({\n      client_id: VERCEL_CLI_CLIENT_ID,\n      grant_type: \"refresh_token\",\n      ...options\n    })\n  });\n}\nasync function processTokenResponse(response) {\n  const json = await response.json();\n  if (!response.ok) {\n    const errorMsg = typeof json === \"object\" && json && \"error\" in json ? String(json.error) : \"Token refresh failed\";\n    return [new Error(errorMsg)];\n  }\n  if (typeof json !== \"object\" || json === null) {\n    return [new Error(\"Invalid token response\")];\n  }\n  if (typeof json.access_token !== \"string\") {\n    return [new Error(\"Missing access_token in response\")];\n  }\n  if (json.token_type !== \"Bearer\") {\n    return [new Error(\"Invalid token_type in response\")];\n  }\n  if (typeof json.expires_in !== \"number\") {\n    return [new Error(\"Missing expires_in in response\")];\n  }\n  return [null, json];\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  processTokenResponse,\n  refreshTokenRequest\n});\n","\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n  // If the importer is in node compatibility mode or this is not an ESM\n  // file that has been converted to a CommonJS file using a Babel-\n  // compatible transform (i.e. \"__esModule\" has not been set), then set\n  // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n  isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n  mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_util_exports = {};\n__export(token_util_exports, {\n  assertVercelOidcTokenResponse: () => assertVercelOidcTokenResponse,\n  findProjectInfo: () => findProjectInfo,\n  getTokenPayload: () => getTokenPayload,\n  getVercelDataDir: () => getVercelDataDir,\n  getVercelOidcToken: () => getVercelOidcToken,\n  getVercelToken: () => getVercelToken,\n  isExpired: () => isExpired,\n  loadToken: () => loadToken,\n  saveToken: () => saveToken\n});\nmodule.exports = __toCommonJS(token_util_exports);\nvar path = __toESM(require(\"path\"));\nvar fs = __toESM(require(\"fs\"));\nvar import_token_error = require(\"./token-error\");\nvar import_token_io = require(\"./token-io\");\nvar import_auth_config = require(\"./auth-config\");\nvar import_oauth = require(\"./oauth\");\nvar import_auth_errors = require(\"./auth-errors\");\nfunction getVercelDataDir() {\n  const vercelFolder = \"com.vercel.cli\";\n  const dataDir = (0, import_token_io.getUserDataDir)();\n  if (!dataDir) {\n    return null;\n  }\n  return path.join(dataDir, vercelFolder);\n}\nasync function getVercelToken(options) {\n  const authConfig = (0, import_auth_config.readAuthConfig)();\n  if (!authConfig?.token) {\n    throw new import_auth_errors.AccessTokenMissingError();\n  }\n  if ((0, import_auth_config.isValidAccessToken)(authConfig, options?.expirationBufferMs)) {\n    return authConfig.token;\n  }\n  if (!authConfig.refreshToken) {\n    (0, import_auth_config.writeAuthConfig)({});\n    throw new import_auth_errors.RefreshAccessTokenFailedError(\"No refresh token available\");\n  }\n  try {\n    const tokenResponse = await (0, import_oauth.refreshTokenRequest)({\n      refresh_token: authConfig.refreshToken\n    });\n    const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse);\n    if (tokensError || !tokens) {\n      (0, import_auth_config.writeAuthConfig)({});\n      throw new import_auth_errors.RefreshAccessTokenFailedError(tokensError);\n    }\n    const updatedConfig = {\n      token: tokens.access_token,\n      expiresAt: Math.floor(Date.now() / 1e3) + tokens.expires_in\n    };\n    if (tokens.refresh_token) {\n      updatedConfig.refreshToken = tokens.refresh_token;\n    }\n    (0, import_auth_config.writeAuthConfig)(updatedConfig);\n    return updatedConfig.token;\n  } catch (error) {\n    (0, import_auth_config.writeAuthConfig)({});\n    if (error instanceof import_auth_errors.AccessTokenMissingError || error instanceof import_auth_errors.RefreshAccessTokenFailedError) {\n      throw error;\n    }\n    throw new import_auth_errors.RefreshAccessTokenFailedError(error);\n  }\n}\nasync function getVercelOidcToken(authToken, projectId, teamId) {\n  const url = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : \"\"}`;\n  const res = await fetch(url, {\n    method: \"POST\",\n    headers: {\n      Authorization: `Bearer ${authToken}`\n    }\n  });\n  if (!res.ok) {\n    throw new import_token_error.VercelOidcTokenError(\n      `Failed to refresh OIDC token: ${res.statusText}`\n    );\n  }\n  const tokenRes = await res.json();\n  assertVercelOidcTokenResponse(tokenRes);\n  return tokenRes;\n}\nfunction assertVercelOidcTokenResponse(res) {\n  if (!res || typeof res !== \"object\") {\n    throw new TypeError(\n      \"Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again\"\n    );\n  }\n  if (!(\"token\" in res) || typeof res.token !== \"string\") {\n    throw new TypeError(\n      \"Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again\"\n    );\n  }\n}\nfunction findProjectInfo() {\n  const dir = (0, import_token_io.findRootDir)();\n  if (!dir) {\n    throw new import_token_error.VercelOidcTokenError(\n      \"Unable to find project root directory. Have you linked your project with `vc link?`\"\n    );\n  }\n  const prjPath = path.join(dir, \".vercel\", \"project.json\");\n  if (!fs.existsSync(prjPath)) {\n    throw new import_token_error.VercelOidcTokenError(\n      \"project.json not found, have you linked your project with `vc link?`\"\n    );\n  }\n  const prj = JSON.parse(fs.readFileSync(prjPath, \"utf8\"));\n  if (typeof prj.projectId !== \"string\" && typeof prj.orgId !== \"string\") {\n    throw new TypeError(\n      \"Expected a string-valued projectId property. Try running `vc link` to re-link your project.\"\n    );\n  }\n  return { projectId: prj.projectId, teamId: prj.orgId };\n}\nfunction saveToken(token, projectId) {\n  const dir = (0, import_token_io.getUserDataDir)();\n  if (!dir) {\n    throw new import_token_error.VercelOidcTokenError(\n      \"Unable to find user data directory. Please reach out to Vercel support.\"\n    );\n  }\n  const tokenPath = path.join(dir, \"com.vercel.token\", `${projectId}.json`);\n  const tokenJson = JSON.stringify(token);\n  fs.mkdirSync(path.dirname(tokenPath), { mode: 504, recursive: true });\n  fs.writeFileSync(tokenPath, tokenJson);\n  fs.chmodSync(tokenPath, 432);\n  return;\n}\nfunction loadToken(projectId) {\n  const dir = (0, import_token_io.getUserDataDir)();\n  if (!dir) {\n    throw new import_token_error.VercelOidcTokenError(\n      \"Unable to find user data directory. Please reach out to Vercel support.\"\n    );\n  }\n  const tokenPath = path.join(dir, \"com.vercel.token\", `${projectId}.json`);\n  if (!fs.existsSync(tokenPath)) {\n    return null;\n  }\n  const token = JSON.parse(fs.readFileSync(tokenPath, \"utf8\"));\n  assertVercelOidcTokenResponse(token);\n  return token;\n}\nfunction getTokenPayload(token) {\n  const tokenParts = token.split(\".\");\n  if (tokenParts.length !== 3) {\n    throw new import_token_error.VercelOidcTokenError(\n      \"Invalid token. Please run `vc env pull` and try again\"\n    );\n  }\n  const base64 = tokenParts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n  const padded = base64.padEnd(\n    base64.length + (4 - base64.length % 4) % 4,\n    \"=\"\n  );\n  return JSON.parse(Buffer.from(padded, \"base64\").toString(\"utf8\"));\n}\nfunction isExpired(token, bufferMs = 0) {\n  return token.exp * 1e3 < Date.now() + bufferMs;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  assertVercelOidcTokenResponse,\n  findProjectInfo,\n  getTokenPayload,\n  getVercelDataDir,\n  getVercelOidcToken,\n  getVercelToken,\n  isExpired,\n  loadToken,\n  saveToken\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar src_exports = {};\n__export(src_exports, {\n  AccessTokenMissingError: () => import_auth_errors.AccessTokenMissingError,\n  RefreshAccessTokenFailedError: () => import_auth_errors.RefreshAccessTokenFailedError,\n  getContext: () => import_get_context.getContext,\n  getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,\n  getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync,\n  getVercelToken: () => import_token_util.getVercelToken\n});\nmodule.exports = __toCommonJS(src_exports);\nvar import_get_vercel_oidc_token = require(\"./get-vercel-oidc-token\");\nvar import_get_context = require(\"./get-context\");\nvar import_auth_errors = require(\"./auth-errors\");\nvar import_token_util = require(\"./token-util\");\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  AccessTokenMissingError,\n  RefreshAccessTokenFailedError,\n  getContext,\n  getVercelOidcToken,\n  getVercelOidcTokenSync,\n  getVercelToken\n});\n","// src/gateway-realtime-auth.ts\nvar GATEWAY_REALTIME_SUBPROTOCOL = \"ai-gateway-realtime.v1\";\nvar GATEWAY_AUTH_SUBPROTOCOL_PREFIX = \"ai-gateway-auth.\";\nvar GATEWAY_TEAM_SUBPROTOCOL_PREFIX = \"ai-gateway-team.\";\nfunction getGatewayRealtimeProtocols(token, options) {\n  const protocols = [\n    GATEWAY_REALTIME_SUBPROTOCOL,\n    `${GATEWAY_AUTH_SUBPROTOCOL_PREFIX}${token}`\n  ];\n  if (options == null ? void 0 : options.teamIdOrSlug) {\n    protocols.push(\n      `${GATEWAY_TEAM_SUBPROTOCOL_PREFIX}${encodeSubprotocolValue(options.teamIdOrSlug)}`\n    );\n  }\n  return protocols;\n}\nfunction getGatewayRealtimeAuthToken(secWebSocketProtocol) {\n  var _a11;\n  return ((_a11 = findProtocol(secWebSocketProtocol, GATEWAY_AUTH_SUBPROTOCOL_PREFIX)) == null ? void 0 : _a11.slice(\n    GATEWAY_AUTH_SUBPROTOCOL_PREFIX.length\n  )) || void 0;\n}\nfunction getGatewayRealtimeTeamIdOrSlug(secWebSocketProtocol) {\n  var _a11;\n  const encoded = (_a11 = findProtocol(\n    secWebSocketProtocol,\n    GATEWAY_TEAM_SUBPROTOCOL_PREFIX\n  )) == null ? void 0 : _a11.slice(GATEWAY_TEAM_SUBPROTOCOL_PREFIX.length);\n  if (!encoded) return void 0;\n  try {\n    return decodeSubprotocolValue(encoded) || void 0;\n  } catch (e) {\n    return void 0;\n  }\n}\nfunction findProtocol(secWebSocketProtocol, prefix) {\n  return secWebSocketProtocol == null ? void 0 : secWebSocketProtocol.split(\",\").map((protocol) => protocol.trim()).find((protocol) => protocol.startsWith(prefix));\n}\nfunction encodeSubprotocolValue(value) {\n  const bytes = new TextEncoder().encode(value);\n  let binary = \"\";\n  for (const byte of bytes) {\n    binary += String.fromCharCode(byte);\n  }\n  return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/u, \"\");\n}\nfunction decodeSubprotocolValue(value) {\n  const base64 = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n  const padding = \"=\".repeat((4 - base64.length % 4) % 4);\n  const binary = atob(`${base64}${padding}`);\n  const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n  return new TextDecoder().decode(bytes);\n}\n\n// src/gateway-provider.ts\nimport {\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler11,\n  createJsonResponseHandler as createJsonResponseHandler10,\n  loadOptionalSetting,\n  postJsonToApi as postJsonToApi8,\n  withoutTrailingSlash,\n  withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\nimport { z as z17 } from \"zod/v4\";\n\n// src/errors/as-gateway-error.ts\nimport { APICallError } from \"@ai-sdk/provider\";\n\n// src/errors/create-gateway-error.ts\nimport { z as z2 } from \"zod/v4\";\n\n// src/errors/gateway-error.ts\nvar marker = \"vercel.ai.gateway.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar GatewayError = class _GatewayError extends (_b = Error, _a = symbol, _b) {\n  constructor({\n    message,\n    statusCode = 500,\n    cause,\n    generationId,\n    isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n    statusCode === 409 || // conflict\n    statusCode === 429 || // too many requests\n    statusCode >= 500)\n    // server error\n  }) {\n    super(generationId ? `${message} [${generationId}]` : message);\n    this[_a] = true;\n    this.statusCode = statusCode;\n    this.cause = cause;\n    this.generationId = generationId;\n    this.isRetryable = isRetryable;\n  }\n  /**\n   * Checks if the given error is a Gateway Error.\n   * @param {unknown} error - The error to check.\n   * @returns {boolean} True if the error is a Gateway Error, false otherwise.\n   */\n  static isInstance(error) {\n    return _GatewayError.hasMarker(error);\n  }\n  static hasMarker(error) {\n    return typeof error === \"object\" && error !== null && symbol in error && error[symbol] === true;\n  }\n};\n\n// src/errors/gateway-authentication-error.ts\nvar name = \"GatewayAuthenticationError\";\nvar marker2 = `vercel.ai.gateway.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2 = symbol2, _b2) {\n  constructor({\n    message = \"Authentication failed\",\n    statusCode = 401,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a2] = true;\n    // used in isInstance\n    this.name = name;\n    this.type = \"authentication_error\";\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol2 in error;\n  }\n  /**\n   * Creates a contextual error message when authentication fails\n   */\n  static createContextualError({\n    apiKeyProvided,\n    oidcTokenProvided,\n    statusCode = 401,\n    cause,\n    generationId\n  }) {\n    let contextualMessage;\n    if (apiKeyProvided) {\n      contextualMessage = `AI Gateway authentication failed: Invalid API key or token.\n\nCreate a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\n\nProvide an API key or Vercel access token via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;\n    } else if (oidcTokenProvided) {\n      contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.\n\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.\n\nAlternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\nor pass a Vercel access token via the 'apiKey' option.`;\n    } else {\n      contextualMessage = `AI Gateway authentication failed: No authentication provided.\n\nOption 1 - API key:\nCreate an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\nProvide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.\n\nOption 2 - Vercel access token:\nPass a Vercel personal access token or Vercel app access token via the 'apiKey' option.\n\nOption 3 - OIDC token:\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;\n    }\n    return new _GatewayAuthenticationError({\n      message: contextualMessage,\n      statusCode,\n      cause,\n      generationId\n    });\n  }\n};\n\n// src/errors/gateway-invalid-request-error.ts\nvar name2 = \"GatewayInvalidRequestError\";\nvar marker3 = `vercel.ai.gateway.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a3 = symbol3, _b3) {\n  constructor({\n    message = \"Invalid request\",\n    statusCode = 400,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a3] = true;\n    // used in isInstance\n    this.name = name2;\n    this.type = \"invalid_request_error\";\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol3 in error;\n  }\n};\n\n// src/errors/gateway-rate-limit-error.ts\nvar name3 = \"GatewayRateLimitError\";\nvar marker4 = `vercel.ai.gateway.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar GatewayRateLimitError = class extends (_b4 = GatewayError, _a4 = symbol4, _b4) {\n  constructor({\n    message = \"Rate limit exceeded\",\n    statusCode = 429,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a4] = true;\n    // used in isInstance\n    this.name = name3;\n    this.type = \"rate_limit_exceeded\";\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol4 in error;\n  }\n};\n\n// src/errors/gateway-model-not-found-error.ts\nimport { z } from \"zod/v4\";\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nvar name4 = \"GatewayModelNotFoundError\";\nvar marker5 = `vercel.ai.gateway.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar modelNotFoundParamSchema = lazySchema(\n  () => zodSchema(\n    z.object({\n      modelId: z.string()\n    })\n  )\n);\nvar _a5, _b5;\nvar GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a5 = symbol5, _b5) {\n  constructor({\n    message = \"Model not found\",\n    statusCode = 404,\n    modelId,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a5] = true;\n    // used in isInstance\n    this.name = name4;\n    this.type = \"model_not_found\";\n    this.modelId = modelId;\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol5 in error;\n  }\n};\n\n// src/errors/gateway-internal-server-error.ts\nvar name5 = \"GatewayInternalServerError\";\nvar marker6 = `vercel.ai.gateway.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar GatewayInternalServerError = class extends (_b6 = GatewayError, _a6 = symbol6, _b6) {\n  constructor({\n    message = \"Internal server error\",\n    statusCode = 500,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a6] = true;\n    // used in isInstance\n    this.name = name5;\n    this.type = \"internal_server_error\";\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol6 in error;\n  }\n};\n\n// src/errors/gateway-failed-dependency-error.ts\nvar name6 = \"GatewayFailedDependencyError\";\nvar marker7 = `vercel.ai.gateway.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar GatewayFailedDependencyError = class extends (_b7 = GatewayError, _a7 = symbol7, _b7) {\n  constructor({\n    message = \"Failed dependency\",\n    statusCode = 424,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a7] = true;\n    // used in isInstance\n    this.name = name6;\n    this.type = \"failed_dependency\";\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol7 in error;\n  }\n};\n\n// src/errors/gateway-forbidden-error.ts\nvar name7 = \"GatewayForbiddenError\";\nvar marker8 = `vercel.ai.gateway.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar GatewayForbiddenError = class extends (_b8 = GatewayError, _a8 = symbol8, _b8) {\n  constructor({\n    message = \"Forbidden\",\n    statusCode = 403,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a8] = true;\n    // used in isInstance\n    this.name = name7;\n    this.type = \"forbidden\";\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol8 in error;\n  }\n};\n\n// src/errors/gateway-response-error.ts\nvar name8 = \"GatewayResponseError\";\nvar marker9 = `vercel.ai.gateway.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar GatewayResponseError = class extends (_b9 = GatewayError, _a9 = symbol9, _b9) {\n  constructor({\n    message = \"Invalid response from Gateway\",\n    statusCode = 502,\n    response,\n    validationError,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a9] = true;\n    // used in isInstance\n    this.name = name8;\n    this.type = \"response_error\";\n    this.response = response;\n    this.validationError = validationError;\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol9 in error;\n  }\n};\n\n// src/errors/create-gateway-error.ts\nimport {\n  lazySchema as lazySchema2,\n  safeValidateTypes,\n  zodSchema as zodSchema2\n} from \"@ai-sdk/provider-utils\";\nasync function createGatewayErrorFromResponse({\n  response,\n  statusCode,\n  defaultMessage = \"Gateway request failed\",\n  cause,\n  authMethod\n}) {\n  var _a11;\n  const parseResult = await safeValidateTypes({\n    value: response,\n    schema: gatewayErrorResponseSchema\n  });\n  if (!parseResult.success) {\n    const rawGenerationId = typeof response === \"object\" && response !== null && \"generationId\" in response ? response.generationId : void 0;\n    return new GatewayResponseError({\n      message: `Invalid error response format: ${defaultMessage}`,\n      statusCode,\n      response,\n      validationError: parseResult.error,\n      cause,\n      generationId: rawGenerationId\n    });\n  }\n  const validatedResponse = parseResult.value;\n  const errorType = validatedResponse.error.type;\n  const message = validatedResponse.error.message;\n  const generationId = (_a11 = validatedResponse.generationId) != null ? _a11 : void 0;\n  switch (errorType) {\n    case \"authentication_error\":\n      return GatewayAuthenticationError.createContextualError({\n        apiKeyProvided: authMethod === \"api-key\",\n        oidcTokenProvided: authMethod === \"oidc\",\n        statusCode,\n        cause,\n        generationId\n      });\n    case \"invalid_request_error\":\n      return new GatewayInvalidRequestError({\n        message,\n        statusCode,\n        cause,\n        generationId\n      });\n    case \"rate_limit_exceeded\":\n      return new GatewayRateLimitError({\n        message,\n        statusCode,\n        cause,\n        generationId\n      });\n    case \"model_not_found\": {\n      const modelResult = await safeValidateTypes({\n        value: validatedResponse.error.param,\n        schema: modelNotFoundParamSchema\n      });\n      return new GatewayModelNotFoundError({\n        message,\n        statusCode,\n        modelId: modelResult.success ? modelResult.value.modelId : void 0,\n        cause,\n        generationId\n      });\n    }\n    case \"internal_server_error\":\n      return new GatewayInternalServerError({\n        message,\n        statusCode,\n        cause,\n        generationId\n      });\n    case \"failed_dependency\":\n      return new GatewayFailedDependencyError({\n        message,\n        statusCode,\n        cause,\n        generationId\n      });\n    case \"forbidden\":\n      return new GatewayForbiddenError({\n        message,\n        statusCode,\n        cause,\n        generationId\n      });\n    default:\n      return new GatewayInternalServerError({\n        message,\n        statusCode,\n        cause,\n        generationId\n      });\n  }\n}\nvar gatewayErrorResponseSchema = lazySchema2(\n  () => zodSchema2(\n    z2.object({\n      error: z2.object({\n        message: z2.string(),\n        type: z2.string().nullish(),\n        param: z2.unknown().nullish(),\n        code: z2.union([z2.string(), z2.number()]).nullish()\n      }),\n      generationId: z2.string().nullish()\n    })\n  )\n);\n\n// src/errors/extract-api-call-response.ts\nfunction extractApiCallResponse(error) {\n  if (error.data !== void 0) {\n    return error.data;\n  }\n  if (error.responseBody != null) {\n    try {\n      return JSON.parse(error.responseBody);\n    } catch (e) {\n      return error.responseBody;\n    }\n  }\n  return {};\n}\n\n// src/errors/gateway-timeout-error.ts\nvar name9 = \"GatewayTimeoutError\";\nvar marker10 = `vercel.ai.gateway.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar GatewayTimeoutError = class _GatewayTimeoutError extends (_b10 = GatewayError, _a10 = symbol10, _b10) {\n  constructor({\n    message = \"Request timed out\",\n    statusCode = 408,\n    cause,\n    generationId\n  } = {}) {\n    super({ message, statusCode, cause, generationId });\n    this[_a10] = true;\n    // used in isInstance\n    this.name = name9;\n    this.type = \"timeout_error\";\n  }\n  static isInstance(error) {\n    return GatewayError.hasMarker(error) && symbol10 in error;\n  }\n  /**\n   * Creates a helpful timeout error message with troubleshooting guidance\n   */\n  static createTimeoutError({\n    originalMessage,\n    statusCode = 408,\n    cause,\n    generationId\n  }) {\n    const message = `Gateway request timed out: ${originalMessage}\n\n    This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;\n    return new _GatewayTimeoutError({\n      message,\n      statusCode,\n      cause,\n      generationId\n    });\n  }\n};\n\n// src/errors/as-gateway-error.ts\nfunction isTimeoutError(error) {\n  if (!(error instanceof Error)) {\n    return false;\n  }\n  const errorCode = error.code;\n  if (typeof errorCode === \"string\") {\n    const undiciTimeoutCodes = [\n      \"UND_ERR_HEADERS_TIMEOUT\",\n      \"UND_ERR_BODY_TIMEOUT\",\n      \"UND_ERR_CONNECT_TIMEOUT\"\n    ];\n    return undiciTimeoutCodes.includes(errorCode);\n  }\n  return false;\n}\nasync function asGatewayError(error, authMethod) {\n  var _a11;\n  if (GatewayError.isInstance(error)) {\n    return error;\n  }\n  if (isTimeoutError(error)) {\n    return GatewayTimeoutError.createTimeoutError({\n      originalMessage: error instanceof Error ? error.message : \"Unknown error\",\n      cause: error\n    });\n  }\n  if (APICallError.isInstance(error)) {\n    if (error.cause && isTimeoutError(error.cause)) {\n      return GatewayTimeoutError.createTimeoutError({\n        originalMessage: error.message,\n        cause: error\n      });\n    }\n    return await createGatewayErrorFromResponse({\n      response: extractApiCallResponse(error),\n      statusCode: (_a11 = error.statusCode) != null ? _a11 : 500,\n      defaultMessage: \"Gateway request failed\",\n      cause: error,\n      authMethod\n    });\n  }\n  return await createGatewayErrorFromResponse({\n    response: {},\n    statusCode: 500,\n    defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : \"Unknown Gateway error\",\n    cause: error,\n    authMethod\n  });\n}\n\n// src/gateway-headers.ts\nvar GATEWAY_AUTH_METHOD_HEADER = \"ai-gateway-auth-method\";\nvar VERCEL_AI_GATEWAY_TEAM_HEADER = \"x-vercel-ai-gateway-team\";\n\n// src/errors/parse-auth-method.ts\nimport { z as z3 } from \"zod/v4\";\nimport {\n  lazySchema as lazySchema3,\n  safeValidateTypes as safeValidateTypes2,\n  zodSchema as zodSchema3\n} from \"@ai-sdk/provider-utils\";\nasync function parseAuthMethod(headers) {\n  const result = await safeValidateTypes2({\n    value: headers[GATEWAY_AUTH_METHOD_HEADER],\n    schema: gatewayAuthMethodSchema\n  });\n  return result.success ? result.value : void 0;\n}\nvar gatewayAuthMethodSchema = lazySchema3(\n  () => zodSchema3(z3.union([z3.literal(\"api-key\"), z3.literal(\"oidc\")]))\n);\n\n// src/gateway-fetch-metadata.ts\nimport {\n  createJsonErrorResponseHandler,\n  createJsonResponseHandler,\n  getFromApi,\n  lazySchema as lazySchema4,\n  resolve,\n  zodSchema as zodSchema4\n} from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\n\n// src/gateway-model-entry.ts\nvar KNOWN_MODEL_TYPES = [\n  \"embedding\",\n  \"image\",\n  \"language\",\n  \"realtime\",\n  \"reranking\",\n  \"speech\",\n  \"transcription\",\n  \"video\"\n];\n\n// src/gateway-fetch-metadata.ts\nvar GatewayFetchMetadata = class {\n  constructor(config) {\n    this.config = config;\n  }\n  async getAvailableModels() {\n    try {\n      const { value } = await getFromApi({\n        url: `${this.config.baseURL}/config`,\n        headers: this.config.headers ? await resolve(this.config.headers) : void 0,\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayAvailableModelsResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z4.any(),\n          errorToMessage: (data) => data\n        }),\n        fetch: this.config.fetch\n      });\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n  async getCredits() {\n    try {\n      const baseUrl = new URL(this.config.baseURL);\n      const { value } = await getFromApi({\n        url: `${baseUrl.origin}/v1/credits`,\n        headers: this.config.headers ? await resolve(this.config.headers) : void 0,\n        successfulResponseHandler: createJsonResponseHandler(\n          gatewayCreditsResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler({\n          errorSchema: z4.any(),\n          errorToMessage: (data) => data\n        }),\n        fetch: this.config.fetch\n      });\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n};\nvar gatewayAvailableModelsResponseSchema = lazySchema4(\n  () => zodSchema4(\n    z4.object({\n      models: z4.array(\n        z4.object({\n          id: z4.string(),\n          name: z4.string(),\n          description: z4.string().nullish(),\n          pricing: z4.object({\n            input: z4.string(),\n            output: z4.string(),\n            input_cache_read: z4.string().nullish(),\n            input_cache_write: z4.string().nullish()\n          }).transform(\n            ({ input, output, input_cache_read, input_cache_write }) => ({\n              input,\n              output,\n              ...input_cache_read ? { cachedInputTokens: input_cache_read } : {},\n              ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}\n            })\n          ).nullish(),\n          specification: z4.object({\n            specificationVersion: z4.literal(\"v4\"),\n            provider: z4.string(),\n            modelId: z4.string()\n          }),\n          modelType: z4.string().nullish()\n        })\n      ).transform(\n        (models) => models.filter(\n          (m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)\n        )\n      )\n    })\n  )\n);\nvar gatewayCreditsResponseSchema = lazySchema4(\n  () => zodSchema4(\n    z4.object({\n      balance: z4.string(),\n      total_used: z4.string()\n    }).transform(({ balance, total_used }) => ({\n      balance,\n      totalUsed: total_used\n    }))\n  )\n);\n\n// src/gateway-spend-report.ts\nimport {\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler2,\n  createJsonResponseHandler as createJsonResponseHandler2,\n  getFromApi as getFromApi2,\n  lazySchema as lazySchema5,\n  resolve as resolve2,\n  zodSchema as zodSchema5\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\nvar GatewaySpendReport = class {\n  constructor(config) {\n    this.config = config;\n  }\n  async getSpendReport(params) {\n    try {\n      const baseUrl = new URL(this.config.baseURL);\n      const searchParams = new URLSearchParams();\n      searchParams.set(\"start_date\", params.startDate);\n      searchParams.set(\"end_date\", params.endDate);\n      if (params.groupBy) {\n        searchParams.set(\"group_by\", params.groupBy);\n      }\n      if (params.datePart) {\n        searchParams.set(\"date_part\", params.datePart);\n      }\n      if (params.userId) {\n        searchParams.set(\"user_id\", params.userId);\n      }\n      if (params.model) {\n        searchParams.set(\"model\", params.model);\n      }\n      if (params.provider) {\n        searchParams.set(\"provider\", params.provider);\n      }\n      if (params.credentialType) {\n        searchParams.set(\"credential_type\", params.credentialType);\n      }\n      if (params.tags && params.tags.length > 0) {\n        searchParams.set(\"tags\", params.tags.join(\",\"));\n      }\n      const { value } = await getFromApi2({\n        url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,\n        headers: this.config.headers ? await resolve2(this.config.headers) : void 0,\n        successfulResponseHandler: createJsonResponseHandler2(\n          gatewaySpendReportResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler2({\n          errorSchema: z5.any(),\n          errorToMessage: (data) => data\n        }),\n        fetch: this.config.fetch\n      });\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n};\nvar gatewaySpendReportResponseSchema = lazySchema5(\n  () => zodSchema5(\n    z5.object({\n      results: z5.array(\n        z5.object({\n          day: z5.string().optional(),\n          hour: z5.string().optional(),\n          user: z5.string().optional(),\n          model: z5.string().optional(),\n          tag: z5.string().optional(),\n          provider: z5.string().optional(),\n          credential_type: z5.enum([\"byok\", \"system\"]).optional(),\n          total_cost: z5.number(),\n          market_cost: z5.number().optional(),\n          input_tokens: z5.number().optional(),\n          output_tokens: z5.number().optional(),\n          cached_input_tokens: z5.number().optional(),\n          cache_creation_input_tokens: z5.number().optional(),\n          reasoning_tokens: z5.number().optional(),\n          request_count: z5.number().optional()\n        }).transform(\n          ({\n            credential_type,\n            total_cost,\n            market_cost,\n            input_tokens,\n            output_tokens,\n            cached_input_tokens,\n            cache_creation_input_tokens,\n            reasoning_tokens,\n            request_count,\n            ...rest\n          }) => ({\n            ...rest,\n            ...credential_type !== void 0 ? { credentialType: credential_type } : {},\n            totalCost: total_cost,\n            ...market_cost !== void 0 ? { marketCost: market_cost } : {},\n            ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},\n            ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},\n            ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},\n            ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},\n            ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},\n            ...request_count !== void 0 ? { requestCount: request_count } : {}\n          })\n        )\n      )\n    })\n  )\n);\n\n// src/gateway-generation-info.ts\nimport {\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler3,\n  createJsonResponseHandler as createJsonResponseHandler3,\n  getFromApi as getFromApi3,\n  lazySchema as lazySchema6,\n  resolve as resolve3,\n  zodSchema as zodSchema6\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar GatewayGenerationInfoFetcher = class {\n  constructor(config) {\n    this.config = config;\n  }\n  async getGenerationInfo(params) {\n    try {\n      const baseUrl = new URL(this.config.baseURL);\n      const { value } = await getFromApi3({\n        url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,\n        headers: this.config.headers ? await resolve3(this.config.headers) : void 0,\n        successfulResponseHandler: createJsonResponseHandler3(\n          gatewayGenerationInfoResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler3({\n          errorSchema: z6.any(),\n          errorToMessage: (data) => data\n        }),\n        fetch: this.config.fetch\n      });\n      return value;\n    } catch (error) {\n      throw await asGatewayError(error);\n    }\n  }\n};\nvar gatewayGenerationInfoResponseSchema = lazySchema6(\n  () => zodSchema6(\n    z6.object({\n      data: z6.object({\n        id: z6.string(),\n        total_cost: z6.number(),\n        upstream_inference_cost: z6.number(),\n        usage: z6.number(),\n        created_at: z6.string(),\n        model: z6.string(),\n        is_byok: z6.boolean(),\n        provider_name: z6.string(),\n        streamed: z6.boolean(),\n        finish_reason: z6.string(),\n        latency: z6.number(),\n        generation_time: z6.number(),\n        native_tokens_prompt: z6.number(),\n        native_tokens_completion: z6.number(),\n        native_tokens_reasoning: z6.number(),\n        native_tokens_cached: z6.number(),\n        native_tokens_cache_creation: z6.number(),\n        billable_web_search_calls: z6.number()\n      }).transform(\n        ({\n          total_cost,\n          upstream_inference_cost,\n          created_at,\n          is_byok,\n          provider_name,\n          finish_reason,\n          generation_time,\n          native_tokens_prompt,\n          native_tokens_completion,\n          native_tokens_reasoning,\n          native_tokens_cached,\n          native_tokens_cache_creation,\n          billable_web_search_calls,\n          ...rest\n        }) => ({\n          ...rest,\n          totalCost: total_cost,\n          upstreamInferenceCost: upstream_inference_cost,\n          createdAt: created_at,\n          isByok: is_byok,\n          providerName: provider_name,\n          finishReason: finish_reason,\n          generationTime: generation_time,\n          promptTokens: native_tokens_prompt,\n          completionTokens: native_tokens_completion,\n          reasoningTokens: native_tokens_reasoning,\n          cachedTokens: native_tokens_cached,\n          cacheCreationTokens: native_tokens_cache_creation,\n          billableWebSearchCalls: billable_web_search_calls\n        })\n      )\n    }).transform(({ data }) => data)\n  )\n);\n\n// src/gateway-language-model.ts\nimport {\n  combineHeaders,\n  createEventSourceResponseHandler,\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler4,\n  createJsonResponseHandler as createJsonResponseHandler4,\n  postJsonToApi,\n  resolve as resolve4,\n  serializeModelOptions,\n  WORKFLOW_SERIALIZE,\n  WORKFLOW_DESERIALIZE\n} from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar GatewayLanguageModel = class _GatewayLanguageModel {\n  constructor(modelId, config) {\n    this.modelId = modelId;\n    this.config = config;\n    this.specificationVersion = \"v4\";\n    this.supportedUrls = { \"*/*\": [/.*/] };\n  }\n  static [WORKFLOW_SERIALIZE](model) {\n    return serializeModelOptions({\n      modelId: model.modelId,\n      config: model.config\n    });\n  }\n  static [WORKFLOW_DESERIALIZE](options) {\n    return new _GatewayLanguageModel(options.modelId, options.config);\n  }\n  get provider() {\n    return this.config.provider;\n  }\n  async getArgs(options) {\n    const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;\n    return {\n      args: this.maybeEncodeFileParts(optionsWithoutSignal),\n      warnings: []\n    };\n  }\n  async doGenerate(options) {\n    const { args, warnings } = await this.getArgs(options);\n    const { abortSignal } = options;\n    const resolvedHeaders = this.config.headers ? await resolve4(this.config.headers) : void 0;\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue: rawResponse\n      } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          options.headers,\n          this.getModelConfigHeaders(this.modelId, false),\n          await resolve4(this.config.o11yHeaders)\n        ),\n        body: args,\n        successfulResponseHandler: createJsonResponseHandler4(z7.any()),\n        failedResponseHandler: createJsonErrorResponseHandler4({\n          errorSchema: z7.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        ...responseBody,\n        request: { body: args },\n        response: { headers: responseHeaders, body: rawResponse },\n        warnings\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  async doStream(options) {\n    const { args, warnings } = await this.getArgs(options);\n    const { abortSignal } = options;\n    const resolvedHeaders = this.config.headers ? await resolve4(this.config.headers) : void 0;\n    try {\n      const { value: response, responseHeaders } = await postJsonToApi({\n        url: this.getUrl(),\n        headers: combineHeaders(\n          resolvedHeaders,\n          options.headers,\n          this.getModelConfigHeaders(this.modelId, true),\n          await resolve4(this.config.o11yHeaders)\n        ),\n        body: args,\n        successfulResponseHandler: createEventSourceResponseHandler(z7.any()),\n        failedResponseHandler: createJsonErrorResponseHandler4({\n          errorSchema: z7.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        stream: response.pipeThrough(\n          new TransformStream({\n            start(controller) {\n              if (warnings.length > 0) {\n                controller.enqueue({ type: \"stream-start\", warnings });\n              }\n            },\n            transform(chunk, controller) {\n              if (chunk.success) {\n                const streamPart = chunk.value;\n                if (streamPart.type === \"raw\" && !options.includeRawChunks) {\n                  return;\n                }\n                if (streamPart.type === \"response-metadata\" && streamPart.timestamp && typeof streamPart.timestamp === \"string\") {\n                  streamPart.timestamp = new Date(streamPart.timestamp);\n                }\n                controller.enqueue(streamPart);\n              } else {\n                controller.error(\n                  chunk.error\n                );\n              }\n            }\n          })\n        ),\n        request: { body: args },\n        response: { headers: responseHeaders }\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  /**\n   * Encodes inline `Uint8Array` file data to a base64 string in place.\n   * @param options - The options to encode.\n   * @returns The options with the file data encoded.\n   */\n  maybeEncodeFileParts(options) {\n    for (const message of options.prompt) {\n      if (!Array.isArray(message.content)) {\n        continue;\n      }\n      for (const part of message.content) {\n        if (part.type === \"file\" || part.type === \"reasoning-file\") {\n          part.data = maybeBase64EncodeFileData(part.data);\n        } else if (part.type === \"tool-result\" && part.output.type === \"content\") {\n          for (const contentPart of part.output.value) {\n            if (contentPart.type === \"file\") {\n              contentPart.data = maybeBase64EncodeFileData(contentPart.data);\n            }\n          }\n        }\n      }\n    }\n    return options;\n  }\n  getUrl() {\n    return `${this.config.baseURL}/language-model`;\n  }\n  getModelConfigHeaders(modelId, streaming) {\n    return {\n      \"ai-language-model-specification-version\": \"4\",\n      \"ai-language-model-id\": modelId,\n      \"ai-language-model-streaming\": String(streaming)\n    };\n  }\n};\nfunction maybeBase64EncodeFileData(data) {\n  if (data.type === \"data\") {\n    const bytes = data.data;\n    if (bytes instanceof Uint8Array) {\n      return { ...data, data: Buffer.from(bytes).toString(\"base64\") };\n    }\n  }\n  return data;\n}\n\n// src/gateway-embedding-model.ts\nimport {\n  combineHeaders as combineHeaders2,\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler5,\n  createJsonResponseHandler as createJsonResponseHandler5,\n  lazySchema as lazySchema7,\n  postJsonToApi as postJsonToApi2,\n  resolve as resolve5,\n  serializeModelOptions as serializeModelOptions2,\n  WORKFLOW_SERIALIZE as WORKFLOW_SERIALIZE2,\n  WORKFLOW_DESERIALIZE as WORKFLOW_DESERIALIZE2,\n  zodSchema as zodSchema7\n} from \"@ai-sdk/provider-utils\";\nimport { z as z8 } from \"zod/v4\";\nvar GatewayEmbeddingModel = class _GatewayEmbeddingModel {\n  constructor(modelId, config) {\n    this.modelId = modelId;\n    this.config = config;\n    this.specificationVersion = \"v4\";\n    this.maxEmbeddingsPerCall = 2048;\n    this.supportsParallelCalls = true;\n  }\n  static [WORKFLOW_SERIALIZE2](model) {\n    return serializeModelOptions2({\n      modelId: model.modelId,\n      config: model.config\n    });\n  }\n  static [WORKFLOW_DESERIALIZE2](options) {\n    return new _GatewayEmbeddingModel(options.modelId, options.config);\n  }\n  get provider() {\n    return this.config.provider;\n  }\n  async doEmbed({\n    values,\n    headers,\n    abortSignal,\n    providerOptions\n  }) {\n    var _a11, _b11;\n    const resolvedHeaders = this.config.headers ? await resolve5(this.config.headers) : void 0;\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue\n      } = await postJsonToApi2({\n        url: this.getUrl(),\n        headers: combineHeaders2(\n          resolvedHeaders,\n          headers != null ? headers : {},\n          this.getModelConfigHeaders(),\n          await resolve5(this.config.o11yHeaders)\n        ),\n        body: {\n          values,\n          ...providerOptions ? { providerOptions } : {}\n        },\n        successfulResponseHandler: createJsonResponseHandler5(\n          gatewayEmbeddingResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler5({\n          errorSchema: z8.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        embeddings: responseBody.embeddings,\n        usage: (_a11 = responseBody.usage) != null ? _a11 : void 0,\n        providerMetadata: responseBody.providerMetadata,\n        response: { headers: responseHeaders, body: rawValue },\n        warnings: (_b11 = responseBody.warnings) != null ? _b11 : []\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  getUrl() {\n    return `${this.config.baseURL}/embedding-model`;\n  }\n  getModelConfigHeaders() {\n    return {\n      \"ai-embedding-model-specification-version\": \"4\",\n      \"ai-model-id\": this.modelId\n    };\n  }\n};\nvar gatewayEmbeddingWarningSchema = z8.discriminatedUnion(\"type\", [\n  z8.object({\n    type: z8.literal(\"unsupported\"),\n    feature: z8.string(),\n    details: z8.string().optional()\n  }),\n  z8.object({\n    type: z8.literal(\"compatibility\"),\n    feature: z8.string(),\n    details: z8.string().optional()\n  }),\n  z8.object({\n    type: z8.literal(\"deprecated\"),\n    setting: z8.string(),\n    message: z8.string()\n  }),\n  z8.object({\n    type: z8.literal(\"other\"),\n    message: z8.string()\n  })\n]);\nvar gatewayEmbeddingResponseSchema = lazySchema7(\n  () => zodSchema7(\n    z8.object({\n      embeddings: z8.array(z8.array(z8.number())),\n      usage: z8.object({ tokens: z8.number() }).nullish(),\n      warnings: z8.array(gatewayEmbeddingWarningSchema).optional(),\n      providerMetadata: z8.record(z8.string(), z8.record(z8.string(), z8.unknown())).optional()\n    })\n  )\n);\n\n// src/gateway-image-model.ts\nimport {\n  combineHeaders as combineHeaders3,\n  convertUint8ArrayToBase64,\n  createJsonResponseHandler as createJsonResponseHandler6,\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler6,\n  postJsonToApi as postJsonToApi3,\n  resolve as resolve6,\n  serializeModelOptions as serializeModelOptions3,\n  WORKFLOW_SERIALIZE as WORKFLOW_SERIALIZE3,\n  WORKFLOW_DESERIALIZE as WORKFLOW_DESERIALIZE3\n} from \"@ai-sdk/provider-utils\";\nimport { z as z9 } from \"zod/v4\";\nvar GatewayImageModel = class _GatewayImageModel {\n  constructor(modelId, config) {\n    this.modelId = modelId;\n    this.config = config;\n    this.specificationVersion = \"v4\";\n    // Set a very large number to prevent client-side splitting of requests\n    this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;\n  }\n  static [WORKFLOW_SERIALIZE3](model) {\n    return serializeModelOptions3({\n      modelId: model.modelId,\n      config: model.config\n    });\n  }\n  static [WORKFLOW_DESERIALIZE3](options) {\n    return new _GatewayImageModel(options.modelId, options.config);\n  }\n  get provider() {\n    return this.config.provider;\n  }\n  async doGenerate({\n    prompt,\n    n,\n    size,\n    aspectRatio,\n    seed,\n    files,\n    mask,\n    providerOptions,\n    headers,\n    abortSignal\n  }) {\n    var _a11, _b11, _c, _d;\n    const resolvedHeaders = this.config.headers ? await resolve6(this.config.headers) : void 0;\n    try {\n      const { responseHeaders, value: responseBody } = await postJsonToApi3({\n        url: this.getUrl(),\n        headers: combineHeaders3(\n          resolvedHeaders,\n          headers != null ? headers : {},\n          this.getModelConfigHeaders(),\n          await resolve6(this.config.o11yHeaders)\n        ),\n        body: {\n          prompt,\n          n,\n          ...size && { size },\n          ...aspectRatio && { aspectRatio },\n          ...seed && { seed },\n          ...providerOptions && { providerOptions },\n          ...files && {\n            files: files.map((file) => maybeEncodeImageFile(file))\n          },\n          ...mask && { mask: maybeEncodeImageFile(mask) }\n        },\n        successfulResponseHandler: createJsonResponseHandler6(\n          gatewayImageResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler6({\n          errorSchema: z9.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        images: responseBody.images,\n        // Always base64 strings from server\n        warnings: (_a11 = responseBody.warnings) != null ? _a11 : [],\n        providerMetadata: responseBody.providerMetadata,\n        response: {\n          timestamp: /* @__PURE__ */ new Date(),\n          modelId: this.modelId,\n          headers: responseHeaders\n        },\n        ...responseBody.usage != null && {\n          usage: {\n            inputTokens: (_b11 = responseBody.usage.inputTokens) != null ? _b11 : void 0,\n            outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,\n            totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0\n          }\n        }\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  getUrl() {\n    return `${this.config.baseURL}/image-model`;\n  }\n  getModelConfigHeaders() {\n    return {\n      \"ai-image-model-specification-version\": \"4\",\n      \"ai-model-id\": this.modelId\n    };\n  }\n};\nfunction maybeEncodeImageFile(file) {\n  if (file.type === \"file\" && file.data instanceof Uint8Array) {\n    return {\n      ...file,\n      data: convertUint8ArrayToBase64(file.data)\n    };\n  }\n  return file;\n}\nvar providerMetadataEntrySchema = z9.object({\n  images: z9.array(z9.unknown()).optional()\n}).catchall(z9.unknown());\nvar gatewayImageWarningSchema = z9.discriminatedUnion(\"type\", [\n  z9.object({\n    type: z9.literal(\"unsupported\"),\n    feature: z9.string(),\n    details: z9.string().optional()\n  }),\n  z9.object({\n    type: z9.literal(\"compatibility\"),\n    feature: z9.string(),\n    details: z9.string().optional()\n  }),\n  z9.object({\n    type: z9.literal(\"deprecated\"),\n    setting: z9.string(),\n    message: z9.string()\n  }),\n  z9.object({\n    type: z9.literal(\"other\"),\n    message: z9.string()\n  })\n]);\nvar gatewayImageUsageSchema = z9.object({\n  inputTokens: z9.number().nullish(),\n  outputTokens: z9.number().nullish(),\n  totalTokens: z9.number().nullish()\n});\nvar gatewayImageResponseSchema = z9.object({\n  images: z9.array(z9.string()),\n  // Always base64 strings over the wire\n  warnings: z9.array(gatewayImageWarningSchema).optional(),\n  providerMetadata: z9.record(z9.string(), providerMetadataEntrySchema).optional(),\n  usage: gatewayImageUsageSchema.optional()\n});\n\n// src/gateway-video-model.ts\nimport {\n  APICallError as APICallError2\n} from \"@ai-sdk/provider\";\nimport {\n  combineHeaders as combineHeaders4,\n  convertUint8ArrayToBase64 as convertUint8ArrayToBase642,\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler7,\n  parseJsonEventStream,\n  postJsonToApi as postJsonToApi4,\n  resolve as resolve7\n} from \"@ai-sdk/provider-utils\";\nimport { z as z10 } from \"zod/v4\";\nvar GatewayVideoModel = class {\n  constructor(modelId, config) {\n    this.modelId = modelId;\n    this.config = config;\n    this.specificationVersion = \"v4\";\n    // Set a very large number to prevent client-side splitting of requests\n    this.maxVideosPerCall = Number.MAX_SAFE_INTEGER;\n  }\n  get provider() {\n    return this.config.provider;\n  }\n  async doGenerate({\n    prompt,\n    n,\n    aspectRatio,\n    resolution,\n    duration,\n    fps,\n    seed,\n    generateAudio,\n    image,\n    providerOptions,\n    headers,\n    abortSignal\n  }) {\n    var _a11;\n    const resolvedHeaders = this.config.headers ? await resolve7(this.config.headers) : void 0;\n    try {\n      const { responseHeaders, value: responseBody } = await postJsonToApi4({\n        url: this.getUrl(),\n        headers: combineHeaders4(\n          resolvedHeaders,\n          headers != null ? headers : {},\n          this.getModelConfigHeaders(),\n          await resolve7(this.config.o11yHeaders),\n          { accept: \"text/event-stream\" }\n        ),\n        body: {\n          prompt,\n          n,\n          ...aspectRatio && { aspectRatio },\n          ...resolution && { resolution },\n          ...duration && { duration },\n          ...fps && { fps },\n          ...seed && { seed },\n          ...generateAudio !== void 0 && { generateAudio },\n          ...providerOptions && { providerOptions },\n          ...image && { image: maybeEncodeVideoFile(image) }\n        },\n        successfulResponseHandler: async ({\n          response,\n          url,\n          requestBodyValues\n        }) => {\n          if (response.body == null) {\n            throw new APICallError2({\n              message: \"SSE response body is empty\",\n              url,\n              requestBodyValues,\n              statusCode: response.status\n            });\n          }\n          const eventStream = parseJsonEventStream({\n            stream: response.body,\n            schema: gatewayVideoEventSchema\n          });\n          const reader = eventStream.getReader();\n          const { done, value: parseResult } = await reader.read();\n          reader.releaseLock();\n          if (done || !parseResult) {\n            throw new APICallError2({\n              message: \"SSE stream ended without a data event\",\n              url,\n              requestBodyValues,\n              statusCode: response.status\n            });\n          }\n          if (!parseResult.success) {\n            throw new APICallError2({\n              message: \"Failed to parse video SSE event\",\n              cause: parseResult.error,\n              url,\n              requestBodyValues,\n              statusCode: response.status\n            });\n          }\n          const event = parseResult.value;\n          if (event.type === \"error\") {\n            throw new APICallError2({\n              message: event.message,\n              statusCode: event.statusCode,\n              url,\n              requestBodyValues,\n              responseHeaders: Object.fromEntries([...response.headers]),\n              responseBody: JSON.stringify(event),\n              data: {\n                error: {\n                  message: event.message,\n                  type: event.errorType,\n                  param: event.param\n                }\n              }\n            });\n          }\n          return {\n            value: {\n              videos: event.videos,\n              warnings: event.warnings,\n              providerMetadata: event.providerMetadata\n            },\n            responseHeaders: Object.fromEntries([...response.headers])\n          };\n        },\n        failedResponseHandler: createJsonErrorResponseHandler7({\n          errorSchema: z10.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        videos: responseBody.videos,\n        warnings: (_a11 = responseBody.warnings) != null ? _a11 : [],\n        providerMetadata: responseBody.providerMetadata,\n        response: {\n          timestamp: /* @__PURE__ */ new Date(),\n          modelId: this.modelId,\n          headers: responseHeaders\n        }\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  getUrl() {\n    return `${this.config.baseURL}/video-model`;\n  }\n  getModelConfigHeaders() {\n    return {\n      \"ai-video-model-specification-version\": \"4\",\n      \"ai-model-id\": this.modelId\n    };\n  }\n};\nfunction maybeEncodeVideoFile(file) {\n  if (file.type === \"file\" && file.data instanceof Uint8Array) {\n    return {\n      ...file,\n      data: convertUint8ArrayToBase642(file.data)\n    };\n  }\n  return file;\n}\nvar providerMetadataEntrySchema2 = z10.object({\n  videos: z10.array(z10.unknown()).optional()\n}).catchall(z10.unknown());\nvar gatewayVideoDataSchema = z10.union([\n  z10.object({\n    type: z10.literal(\"url\"),\n    url: z10.string(),\n    mediaType: z10.string()\n  }),\n  z10.object({\n    type: z10.literal(\"base64\"),\n    data: z10.string(),\n    mediaType: z10.string()\n  })\n]);\nvar gatewayVideoWarningSchema = z10.discriminatedUnion(\"type\", [\n  z10.object({\n    type: z10.literal(\"unsupported\"),\n    feature: z10.string(),\n    details: z10.string().optional()\n  }),\n  z10.object({\n    type: z10.literal(\"compatibility\"),\n    feature: z10.string(),\n    details: z10.string().optional()\n  }),\n  z10.object({\n    type: z10.literal(\"deprecated\"),\n    setting: z10.string(),\n    message: z10.string()\n  }),\n  z10.object({\n    type: z10.literal(\"other\"),\n    message: z10.string()\n  })\n]);\nvar gatewayVideoEventSchema = z10.discriminatedUnion(\"type\", [\n  z10.object({\n    type: z10.literal(\"result\"),\n    videos: z10.array(gatewayVideoDataSchema),\n    warnings: z10.array(gatewayVideoWarningSchema).optional(),\n    providerMetadata: z10.record(z10.string(), providerMetadataEntrySchema2).optional()\n  }),\n  z10.object({\n    type: z10.literal(\"error\"),\n    message: z10.string(),\n    errorType: z10.string(),\n    statusCode: z10.number(),\n    param: z10.unknown().nullable()\n  })\n]);\n\n// src/gateway-reranking-model.ts\nimport {\n  combineHeaders as combineHeaders5,\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler8,\n  createJsonResponseHandler as createJsonResponseHandler7,\n  lazySchema as lazySchema8,\n  postJsonToApi as postJsonToApi5,\n  resolve as resolve8,\n  zodSchema as zodSchema8\n} from \"@ai-sdk/provider-utils\";\nimport { z as z11 } from \"zod/v4\";\nvar GatewayRerankingModel = class {\n  constructor(modelId, config) {\n    this.modelId = modelId;\n    this.config = config;\n    this.specificationVersion = \"v4\";\n  }\n  get provider() {\n    return this.config.provider;\n  }\n  async doRerank({\n    documents,\n    query,\n    topN,\n    headers,\n    abortSignal,\n    providerOptions\n  }) {\n    var _a11;\n    const resolvedHeaders = this.config.headers ? await resolve8(this.config.headers) : void 0;\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue\n      } = await postJsonToApi5({\n        url: this.getUrl(),\n        headers: combineHeaders5(\n          resolvedHeaders,\n          headers != null ? headers : {},\n          this.getModelConfigHeaders(),\n          await resolve8(this.config.o11yHeaders)\n        ),\n        body: {\n          documents,\n          query,\n          ...topN != null ? { topN } : {},\n          ...providerOptions ? { providerOptions } : {}\n        },\n        successfulResponseHandler: createJsonResponseHandler7(\n          gatewayRerankingResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler8({\n          errorSchema: z11.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        ranking: responseBody.ranking,\n        providerMetadata: responseBody.providerMetadata,\n        response: { headers: responseHeaders, body: rawValue },\n        warnings: (_a11 = responseBody.warnings) != null ? _a11 : []\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  getUrl() {\n    return `${this.config.baseURL}/reranking-model`;\n  }\n  getModelConfigHeaders() {\n    return {\n      \"ai-reranking-model-specification-version\": \"4\",\n      \"ai-model-id\": this.modelId\n    };\n  }\n};\nvar gatewayRerankingWarningSchema = z11.discriminatedUnion(\"type\", [\n  z11.object({\n    type: z11.literal(\"unsupported\"),\n    feature: z11.string(),\n    details: z11.string().optional()\n  }),\n  z11.object({\n    type: z11.literal(\"compatibility\"),\n    feature: z11.string(),\n    details: z11.string().optional()\n  }),\n  z11.object({\n    type: z11.literal(\"deprecated\"),\n    setting: z11.string(),\n    message: z11.string()\n  }),\n  z11.object({\n    type: z11.literal(\"other\"),\n    message: z11.string()\n  })\n]);\nvar gatewayRerankingResponseSchema = lazySchema8(\n  () => zodSchema8(\n    z11.object({\n      ranking: z11.array(\n        z11.object({\n          index: z11.number(),\n          relevanceScore: z11.number()\n        })\n      ),\n      warnings: z11.array(gatewayRerankingWarningSchema).optional(),\n      providerMetadata: z11.record(z11.string(), z11.record(z11.string(), z11.unknown())).optional()\n    })\n  )\n);\n\n// src/gateway-speech-model.ts\nimport {\n  combineHeaders as combineHeaders6,\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler9,\n  createJsonResponseHandler as createJsonResponseHandler8,\n  postJsonToApi as postJsonToApi6,\n  resolve as resolve9\n} from \"@ai-sdk/provider-utils\";\nimport { z as z12 } from \"zod/v4\";\nvar GatewaySpeechModel = class {\n  constructor(modelId, config) {\n    this.modelId = modelId;\n    this.config = config;\n    this.specificationVersion = \"v4\";\n  }\n  get provider() {\n    return this.config.provider;\n  }\n  async doGenerate({\n    text,\n    voice,\n    outputFormat,\n    instructions,\n    speed,\n    language,\n    providerOptions,\n    headers,\n    abortSignal\n  }) {\n    var _a11;\n    const resolvedHeaders = this.config.headers ? await resolve9(this.config.headers) : void 0;\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue\n      } = await postJsonToApi6({\n        url: this.getUrl(),\n        headers: combineHeaders6(\n          resolvedHeaders,\n          headers != null ? headers : {},\n          this.getModelConfigHeaders(),\n          await resolve9(this.config.o11yHeaders)\n        ),\n        body: {\n          text,\n          ...voice && { voice },\n          ...outputFormat && { outputFormat },\n          ...instructions && { instructions },\n          ...speed != null && { speed },\n          ...language && { language },\n          ...providerOptions && { providerOptions }\n        },\n        successfulResponseHandler: createJsonResponseHandler8(\n          gatewaySpeechResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler9({\n          errorSchema: z12.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        audio: responseBody.audio,\n        warnings: (_a11 = responseBody.warnings) != null ? _a11 : [],\n        providerMetadata: responseBody.providerMetadata,\n        response: {\n          timestamp: /* @__PURE__ */ new Date(),\n          modelId: this.modelId,\n          headers: responseHeaders,\n          body: rawValue\n        }\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  getUrl() {\n    return `${this.config.baseURL}/speech-model`;\n  }\n  getModelConfigHeaders() {\n    return {\n      \"ai-speech-model-specification-version\": \"4\",\n      \"ai-model-id\": this.modelId\n    };\n  }\n};\nvar providerMetadataEntrySchema3 = z12.object({}).catchall(z12.unknown());\nvar gatewaySpeechWarningSchema = z12.discriminatedUnion(\"type\", [\n  z12.object({\n    type: z12.literal(\"unsupported\"),\n    feature: z12.string(),\n    details: z12.string().optional()\n  }),\n  z12.object({\n    type: z12.literal(\"compatibility\"),\n    feature: z12.string(),\n    details: z12.string().optional()\n  }),\n  z12.object({\n    type: z12.literal(\"deprecated\"),\n    setting: z12.string(),\n    message: z12.string()\n  }),\n  z12.object({\n    type: z12.literal(\"other\"),\n    message: z12.string()\n  })\n]);\nvar gatewaySpeechResponseSchema = z12.object({\n  audio: z12.string(),\n  warnings: z12.array(gatewaySpeechWarningSchema).optional(),\n  providerMetadata: z12.record(z12.string(), providerMetadataEntrySchema3).optional()\n});\n\n// src/gateway-transcription-model.ts\nimport {\n  combineHeaders as combineHeaders7,\n  convertUint8ArrayToBase64 as convertUint8ArrayToBase643,\n  createJsonErrorResponseHandler as createJsonErrorResponseHandler10,\n  createJsonResponseHandler as createJsonResponseHandler9,\n  postJsonToApi as postJsonToApi7,\n  resolve as resolve10\n} from \"@ai-sdk/provider-utils\";\nimport { z as z13 } from \"zod/v4\";\nvar GatewayTranscriptionModel = class {\n  constructor(modelId, config) {\n    this.modelId = modelId;\n    this.config = config;\n    this.specificationVersion = \"v4\";\n  }\n  get provider() {\n    return this.config.provider;\n  }\n  async doGenerate({\n    audio,\n    mediaType,\n    providerOptions,\n    headers,\n    abortSignal\n  }) {\n    var _a11, _b11, _c, _d;\n    const resolvedHeaders = this.config.headers ? await resolve10(this.config.headers) : void 0;\n    try {\n      const {\n        responseHeaders,\n        value: responseBody,\n        rawValue\n      } = await postJsonToApi7({\n        url: this.getUrl(),\n        headers: combineHeaders7(\n          resolvedHeaders,\n          headers != null ? headers : {},\n          this.getModelConfigHeaders(),\n          await resolve10(this.config.o11yHeaders)\n        ),\n        body: {\n          audio: audio instanceof Uint8Array ? convertUint8ArrayToBase643(audio) : audio,\n          mediaType,\n          ...providerOptions && { providerOptions }\n        },\n        successfulResponseHandler: createJsonResponseHandler9(\n          gatewayTranscriptionResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler10({\n          errorSchema: z13.any(),\n          errorToMessage: (data) => data\n        }),\n        ...abortSignal && { abortSignal },\n        fetch: this.config.fetch\n      });\n      return {\n        text: responseBody.text,\n        segments: (_a11 = responseBody.segments) != null ? _a11 : [],\n        language: (_b11 = responseBody.language) != null ? _b11 : void 0,\n        durationInSeconds: (_c = responseBody.durationInSeconds) != null ? _c : void 0,\n        warnings: (_d = responseBody.warnings) != null ? _d : [],\n        providerMetadata: responseBody.providerMetadata,\n        response: {\n          timestamp: /* @__PURE__ */ new Date(),\n          modelId: this.modelId,\n          headers: responseHeaders,\n          body: rawValue\n        }\n      };\n    } catch (error) {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {})\n      );\n    }\n  }\n  getUrl() {\n    return `${this.config.baseURL}/transcription-model`;\n  }\n  getModelConfigHeaders() {\n    return {\n      \"ai-transcription-model-specification-version\": \"4\",\n      \"ai-model-id\": this.modelId\n    };\n  }\n};\nvar providerMetadataEntrySchema4 = z13.object({}).catchall(z13.unknown());\nvar gatewayTranscriptionWarningSchema = z13.discriminatedUnion(\"type\", [\n  z13.object({\n    type: z13.literal(\"unsupported\"),\n    feature: z13.string(),\n    details: z13.string().optional()\n  }),\n  z13.object({\n    type: z13.literal(\"compatibility\"),\n    feature: z13.string(),\n    details: z13.string().optional()\n  }),\n  z13.object({\n    type: z13.literal(\"deprecated\"),\n    setting: z13.string(),\n    message: z13.string()\n  }),\n  z13.object({\n    type: z13.literal(\"other\"),\n    message: z13.string()\n  })\n]);\nvar gatewayTranscriptionResponseSchema = z13.object({\n  text: z13.string(),\n  segments: z13.array(\n    z13.object({\n      text: z13.string(),\n      startSecond: z13.number(),\n      endSecond: z13.number()\n    })\n  ).optional(),\n  language: z13.string().nullish(),\n  durationInSeconds: z13.number().nullish(),\n  warnings: z13.array(gatewayTranscriptionWarningSchema).optional(),\n  providerMetadata: z13.record(z13.string(), providerMetadataEntrySchema4).optional()\n});\n\n// src/gateway-realtime-model.ts\nvar GatewayRealtimeModel = class {\n  constructor(modelId, config) {\n    this.specificationVersion = \"v4\";\n    this.modelId = modelId;\n    this.provider = config.provider;\n    this.config = config;\n  }\n  /**\n   * Mints a single-use, short-lived client secret (`vcst_`) the browser uses to\n   * open the realtime WebSocket without ever holding the long-lived Gateway\n   * credential. The customer's server calls this (via\n   * `gateway.experimental_realtime.getToken`) and hands the returned token to\n   * the browser, which connects with it through the `ai-gateway-auth.<token>`\n   * subprotocol. `expiresAfterSeconds` is forwarded to the mint endpoint;\n   * `sessionConfig` is intentionally unused here — it is applied later via the\n   * normalized `session-update` event.\n   */\n  async doCreateClientSecret(options) {\n    const secret = await this.config.createClientSecret({\n      modelId: this.modelId,\n      ...(options == null ? void 0 : options.expiresAfterSeconds) != null && {\n        expiresAfterSeconds: options.expiresAfterSeconds\n      }\n    });\n    return {\n      token: secret.token,\n      url: toGatewayRealtimeUrl(this.config.baseURL, this.modelId),\n      ...secret.expiresAt != null && { expiresAt: secret.expiresAt }\n    };\n  }\n  getWebSocketConfig(options) {\n    return {\n      url: options.url,\n      protocols: getGatewayRealtimeProtocols(options.token, {\n        teamIdOrSlug: this.config.teamIdOrSlug\n      })\n    };\n  }\n  parseServerEvent(raw) {\n    return raw;\n  }\n  serializeClientEvent(event) {\n    return event;\n  }\n  buildSessionConfig(config) {\n    return config;\n  }\n};\nfunction toGatewayRealtimeUrl(baseURL, modelId) {\n  const url = new URL(`${baseURL.replace(/^http/, \"ws\")}/realtime-model`);\n  url.searchParams.set(\"ai-model-id\", modelId);\n  return url.toString();\n}\n\n// src/tool/exa-search.ts\nimport {\n  createProviderExecutedToolFactory,\n  lazySchema as lazySchema9,\n  zodSchema as zodSchema9\n} from \"@ai-sdk/provider-utils\";\nimport { z as z14 } from \"zod\";\nvar exaSearchInputSchema = lazySchema9(\n  () => zodSchema9(\n    z14.object({\n      query: z14.string().describe(\"Natural-language web search query. This is required.\"),\n      type: z14.enum([\"auto\", \"fast\", \"instant\"]).optional().describe(\n        \"Search method. Use auto for the default balance of speed and quality.\"\n      ),\n      num_results: z14.number().optional().describe(\"Maximum number of results to return (1-100, default: 10).\"),\n      category: z14.enum([\n        \"company\",\n        \"people\",\n        \"research paper\",\n        \"news\",\n        \"personal site\",\n        \"financial report\"\n      ]).optional().describe(\"Optional content category to focus results.\"),\n      user_location: z14.string().optional().describe(\"Two-letter ISO country code such as 'US'.\"),\n      include_domains: z14.array(z14.string()).optional().describe(\"Only return results from these domains.\"),\n      exclude_domains: z14.array(z14.string()).optional().describe(\"Exclude results from these domains.\"),\n      start_published_date: z14.string().optional().describe(\"Only return links published after this ISO 8601 date.\"),\n      end_published_date: z14.string().optional().describe(\"Only return links published before this ISO 8601 date.\"),\n      contents: z14.object({\n        text: z14.union([\n          z14.boolean(),\n          z14.object({\n            max_characters: z14.number().optional(),\n            include_html_tags: z14.boolean().optional(),\n            verbosity: z14.enum([\"compact\", \"standard\", \"full\"]).optional(),\n            include_sections: z14.array(\n              z14.enum([\n                \"header\",\n                \"navigation\",\n                \"banner\",\n                \"body\",\n                \"sidebar\",\n                \"footer\",\n                \"metadata\"\n              ])\n            ).optional(),\n            exclude_sections: z14.array(\n              z14.enum([\n                \"header\",\n                \"navigation\",\n                \"banner\",\n                \"body\",\n                \"sidebar\",\n                \"footer\",\n                \"metadata\"\n              ])\n            ).optional()\n          })\n        ]).optional(),\n        highlights: z14.union([\n          z14.boolean(),\n          z14.object({\n            query: z14.string().optional(),\n            max_characters: z14.number().optional()\n          })\n        ]).optional(),\n        max_age_hours: z14.number().optional(),\n        livecrawl_timeout: z14.number().optional(),\n        subpages: z14.number().optional(),\n        subpage_target: z14.union([z14.string(), z14.array(z14.string())]).optional(),\n        extras: z14.object({\n          links: z14.number().optional(),\n          image_links: z14.number().optional()\n        }).optional()\n      }).optional().describe(\"Controls extracted page content and freshness.\")\n    })\n  )\n);\nvar exaSearchOutputSchema = lazySchema9(\n  () => zodSchema9(\n    z14.union([\n      z14.object({\n        requestId: z14.string(),\n        searchType: z14.string().optional(),\n        resolvedSearchType: z14.string().optional(),\n        results: z14.array(\n          z14.object({\n            title: z14.string(),\n            url: z14.string(),\n            id: z14.string(),\n            publishedDate: z14.string().nullable().optional(),\n            author: z14.string().nullable().optional(),\n            image: z14.string().nullable().optional(),\n            favicon: z14.string().nullable().optional(),\n            text: z14.string().optional(),\n            highlights: z14.array(z14.string()).optional(),\n            highlightScores: z14.array(z14.number()).optional(),\n            summary: z14.string().optional(),\n            subpages: z14.array(z14.any()).optional(),\n            extras: z14.object({\n              links: z14.array(z14.string()).optional(),\n              imageLinks: z14.array(z14.string()).optional()\n            }).optional()\n          })\n        ),\n        costDollars: z14.object({\n          total: z14.number().optional(),\n          search: z14.record(z14.number()).optional()\n        }).optional()\n      }),\n      z14.object({\n        error: z14.enum([\n          \"api_error\",\n          \"rate_limit\",\n          \"timeout\",\n          \"invalid_input\",\n          \"configuration_error\",\n          \"execution_error\",\n          \"unknown\"\n        ]),\n        statusCode: z14.number().optional(),\n        message: z14.string()\n      })\n    ])\n  )\n);\nvar exaSearchToolFactory = createProviderExecutedToolFactory({\n  id: \"gateway.exa_search\",\n  inputSchema: exaSearchInputSchema,\n  outputSchema: exaSearchOutputSchema\n});\nvar exaSearch = (config = {}) => exaSearchToolFactory(config);\n\n// src/tool/parallel-search.ts\nimport {\n  createProviderExecutedToolFactory as createProviderExecutedToolFactory2,\n  lazySchema as lazySchema10,\n  zodSchema as zodSchema10\n} from \"@ai-sdk/provider-utils\";\nimport { z as z15 } from \"zod\";\nvar parallelSearchInputSchema = lazySchema10(\n  () => zodSchema10(\n    z15.object({\n      objective: z15.string().describe(\n        \"Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters.\"\n      ),\n      search_queries: z15.array(z15.string()).optional().describe(\n        \"Optional search queries to supplement the objective. Maximum 200 characters per query.\"\n      ),\n      mode: z15.enum([\"one-shot\", \"agentic\"]).optional().describe(\n        'Mode preset: \"one-shot\" for comprehensive results with longer excerpts (default), \"agentic\" for concise, token-efficient results for multi-step workflows.'\n      ),\n      max_results: z15.number().optional().describe(\n        \"Maximum number of results to return (1-20). Defaults to 10 if not specified.\"\n      ),\n      source_policy: z15.object({\n        include_domains: z15.array(z15.string()).optional().describe(\n          \"Limit results to these domains. Use plain domain names only \\u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page).\"\n        ),\n        exclude_domains: z15.array(z15.string()).optional().describe(\n          \"Exclude results from these domains. Use plain domain names only \\u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page).\"\n        ),\n        after_date: z15.string().optional().describe(\n          \"Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.\"\n        )\n      }).optional().describe(\n        \"Source policy for controlling which domains to include/exclude and freshness.\"\n      ),\n      excerpts: z15.object({\n        max_chars_per_result: z15.number().optional().describe(\"Maximum characters per result.\"),\n        max_chars_total: z15.number().optional().describe(\"Maximum total characters across all results.\")\n      }).optional().describe(\"Excerpt configuration for controlling result length.\"),\n      fetch_policy: z15.object({\n        max_age_seconds: z15.number().optional().describe(\n          \"Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.\"\n        )\n      }).optional().describe(\"Fetch policy for controlling content freshness.\")\n    })\n  )\n);\nvar parallelSearchOutputSchema = lazySchema10(\n  () => zodSchema10(\n    z15.union([\n      // Success response\n      z15.object({\n        searchId: z15.string(),\n        results: z15.array(\n          z15.object({\n            url: z15.string(),\n            title: z15.string(),\n            excerpt: z15.string(),\n            publishDate: z15.string().nullable().optional(),\n            relevanceScore: z15.number().optional()\n          })\n        )\n      }),\n      // Error response\n      z15.object({\n        error: z15.enum([\n          \"api_error\",\n          \"rate_limit\",\n          \"timeout\",\n          \"invalid_input\",\n          \"configuration_error\",\n          \"unknown\"\n        ]),\n        statusCode: z15.number().optional(),\n        message: z15.string()\n      })\n    ])\n  )\n);\nvar parallelSearchToolFactory = createProviderExecutedToolFactory2({\n  id: \"gateway.parallel_search\",\n  inputSchema: parallelSearchInputSchema,\n  outputSchema: parallelSearchOutputSchema\n});\nvar parallelSearch = (config = {}) => parallelSearchToolFactory(config);\n\n// src/tool/perplexity-search.ts\nimport {\n  createProviderExecutedToolFactory as createProviderExecutedToolFactory3,\n  lazySchema as lazySchema11,\n  zodSchema as zodSchema11\n} from \"@ai-sdk/provider-utils\";\nimport { z as z16 } from \"zod\";\nvar perplexitySearchInputSchema = lazySchema11(\n  () => zodSchema11(\n    z16.object({\n      query: z16.union([z16.string(), z16.array(z16.string())]).describe(\n        \"Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries.\"\n      ),\n      max_results: z16.number().optional().describe(\n        \"Maximum number of search results to return (1-20, default: 10)\"\n      ),\n      max_tokens_per_page: z16.number().optional().describe(\n        \"Maximum number of tokens to extract per search result page (256-2048, default: 2048)\"\n      ),\n      max_tokens: z16.number().optional().describe(\n        \"Maximum total tokens across all search results (default: 25000, max: 1000000)\"\n      ),\n      country: z16.string().optional().describe(\n        \"Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')\"\n      ),\n      search_domain_filter: z16.array(z16.string()).optional().describe(\n        \"List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']\"\n      ),\n      search_language_filter: z16.array(z16.string()).optional().describe(\n        \"List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']\"\n      ),\n      search_after_date: z16.string().optional().describe(\n        \"Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\"\n      ),\n      search_before_date: z16.string().optional().describe(\n        \"Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\"\n      ),\n      last_updated_after_filter: z16.string().optional().describe(\n        \"Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\"\n      ),\n      last_updated_before_filter: z16.string().optional().describe(\n        \"Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\"\n      ),\n      search_recency_filter: z16.enum([\"day\", \"week\", \"month\", \"year\"]).optional().describe(\n        \"Filter results by relative time period. Cannot be used with search_after_date or search_before_date.\"\n      )\n    })\n  )\n);\nvar perplexitySearchOutputSchema = lazySchema11(\n  () => zodSchema11(\n    z16.union([\n      // Success response\n      z16.object({\n        results: z16.array(\n          z16.object({\n            title: z16.string(),\n            url: z16.string(),\n            snippet: z16.string(),\n            date: z16.string().optional(),\n            lastUpdated: z16.string().optional()\n          })\n        ),\n        id: z16.string()\n      }),\n      // Error response\n      z16.object({\n        error: z16.enum([\n          \"api_error\",\n          \"rate_limit\",\n          \"timeout\",\n          \"invalid_input\",\n          \"unknown\"\n        ]),\n        statusCode: z16.number().optional(),\n        message: z16.string()\n      })\n    ])\n  )\n);\nvar perplexitySearchToolFactory = createProviderExecutedToolFactory3({\n  id: \"gateway.perplexity_search\",\n  inputSchema: perplexitySearchInputSchema,\n  outputSchema: perplexitySearchOutputSchema\n});\nvar perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);\n\n// src/gateway-tools.ts\nvar gatewayTools = {\n  /**\n   * Search the web using Exa for current information and token-efficient\n   * excerpts optimized for agent workflows.\n   *\n   * Supports search type, category, domain, date, location, and content\n   * extraction controls.\n   */\n  exaSearch,\n  /**\n   * Search the web using Parallel AI's Search API for LLM-optimized excerpts.\n   *\n   * Takes a natural language objective and returns relevant excerpts,\n   * replacing multiple keyword searches with a single call for broad\n   * or complex queries. Supports different search types for depth vs\n   * breadth tradeoffs.\n   */\n  parallelSearch,\n  /**\n   * Search the web using Perplexity's Search API for real-time information,\n   * news, research papers, and articles.\n   *\n   * Provides ranked search results with advanced filtering options including\n   * domain, language, date range, and recency filters.\n   */\n  perplexitySearch\n};\n\n// src/vercel-environment.ts\nimport { getContext } from \"@vercel/oidc\";\nimport { getVercelOidcToken } from \"@vercel/oidc\";\nasync function getVercelRequestId() {\n  var _a11;\n  return (_a11 = getContext().headers) == null ? void 0 : _a11[\"x-vercel-id\"];\n}\n\n// src/version.ts\nvar VERSION = true ? \"4.0.4\" : \"0.0.0-test\";\n\n// src/gateway-provider.ts\nvar AI_GATEWAY_PROTOCOL_VERSION = \"0.0.1\";\nvar gatewayClientSecretResponseSchema = z17.object({\n  token: z17.string(),\n  expiresAt: z17.number().nullish()\n});\nfunction createGateway(options = {}) {\n  var _a11, _b11;\n  let pendingMetadata = null;\n  let metadataCache = null;\n  const cacheRefreshMillis = (_a11 = options.metadataCacheRefreshMillis) != null ? _a11 : 1e3 * 60 * 5;\n  let lastFetchTime = 0;\n  const baseURL = (_b11 = withoutTrailingSlash(options.baseURL)) != null ? _b11 : \"https://ai-gateway.vercel.sh/v4/ai\";\n  const createAuthHeaders = (auth) => withUserAgentSuffix(\n    {\n      Authorization: `Bearer ${auth.token}`,\n      \"ai-gateway-protocol-version\": AI_GATEWAY_PROTOCOL_VERSION,\n      [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,\n      ...options.teamIdOrSlug != null ? { [VERCEL_AI_GATEWAY_TEAM_HEADER]: options.teamIdOrSlug } : {},\n      ...options.headers\n    },\n    `ai-sdk/gateway/${VERSION}`\n  );\n  const getHeaders = async () => {\n    try {\n      return createAuthHeaders(await getGatewayAuthToken(options));\n    } catch (error) {\n      throw GatewayAuthenticationError.createContextualError({\n        apiKeyProvided: false,\n        oidcTokenProvided: false,\n        statusCode: 401,\n        cause: error\n      });\n    }\n  };\n  const getRealtimeAuthToken = async () => {\n    try {\n      return await getGatewayAuthToken(options);\n    } catch (error) {\n      throw GatewayAuthenticationError.createContextualError({\n        apiKeyProvided: false,\n        oidcTokenProvided: false,\n        statusCode: 401,\n        cause: error\n      });\n    }\n  };\n  const mintRealtimeClientSecret = async (params) => {\n    assertGatewayRealtimeServerEnvironment();\n    const auth = await getRealtimeAuthToken();\n    const headers = createAuthHeaders(auth);\n    const url = new URL(\"/v1/realtime/client-secrets\", baseURL).toString();\n    try {\n      const { value } = await postJsonToApi8({\n        url,\n        headers,\n        body: {\n          model: params.modelId,\n          ...params.expiresAfterSeconds != null && {\n            expiresIn: params.expiresAfterSeconds\n          }\n        },\n        successfulResponseHandler: createJsonResponseHandler10(\n          gatewayClientSecretResponseSchema\n        ),\n        failedResponseHandler: createJsonErrorResponseHandler11({\n          errorSchema: z17.any(),\n          errorToMessage: (data) => data\n        }),\n        fetch: options.fetch\n      });\n      return {\n        token: value.token,\n        ...value.expiresAt != null && { expiresAt: value.expiresAt }\n      };\n    } catch (error) {\n      throw await asGatewayError(error, await parseAuthMethod(headers));\n    }\n  };\n  const createO11yHeaders = () => {\n    const deploymentId = loadOptionalSetting({\n      settingValue: void 0,\n      environmentVariableName: \"VERCEL_DEPLOYMENT_ID\"\n    });\n    const environment = loadOptionalSetting({\n      settingValue: void 0,\n      environmentVariableName: \"VERCEL_ENV\"\n    });\n    const region = loadOptionalSetting({\n      settingValue: void 0,\n      environmentVariableName: \"VERCEL_REGION\"\n    });\n    const projectId = loadOptionalSetting({\n      settingValue: void 0,\n      environmentVariableName: \"VERCEL_PROJECT_ID\"\n    });\n    return async () => {\n      const requestId = await getVercelRequestId();\n      return {\n        ...deploymentId && { \"ai-o11y-deployment-id\": deploymentId },\n        ...environment && { \"ai-o11y-environment\": environment },\n        ...region && { \"ai-o11y-region\": region },\n        ...requestId && { \"ai-o11y-request-id\": requestId },\n        ...projectId && { \"ai-o11y-project-id\": projectId }\n      };\n    };\n  };\n  const createLanguageModel = (modelId) => {\n    return new GatewayLanguageModel(modelId, {\n      provider: \"gateway\",\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders()\n    });\n  };\n  const getAvailableModels = async () => {\n    var _a12, _b12, _c;\n    const now = (_c = (_b12 = (_a12 = options._internal) == null ? void 0 : _a12.currentDate) == null ? void 0 : _b12.call(_a12).getTime()) != null ? _c : Date.now();\n    if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {\n      lastFetchTime = now;\n      pendingMetadata = new GatewayFetchMetadata({\n        baseURL,\n        headers: getHeaders,\n        fetch: options.fetch\n      }).getAvailableModels().then((metadata) => {\n        metadataCache = metadata;\n        return metadata;\n      }).catch(async (error) => {\n        throw await asGatewayError(\n          error,\n          await parseAuthMethod(await getHeaders())\n        );\n      });\n    }\n    return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;\n  };\n  const getCredits = async () => {\n    return new GatewayFetchMetadata({\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch\n    }).getCredits().catch(async (error) => {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(await getHeaders())\n      );\n    });\n  };\n  const getSpendReport = async (params) => {\n    return new GatewaySpendReport({\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch\n    }).getSpendReport(params).catch(async (error) => {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(await getHeaders())\n      );\n    });\n  };\n  const getGenerationInfo = async (params) => {\n    return new GatewayGenerationInfoFetcher({\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch\n    }).getGenerationInfo(params).catch(async (error) => {\n      throw await asGatewayError(\n        error,\n        await parseAuthMethod(await getHeaders())\n      );\n    });\n  };\n  const provider = function(modelId) {\n    if (new.target) {\n      throw new Error(\n        \"The Gateway Provider model function cannot be called with the new keyword.\"\n      );\n    }\n    return createLanguageModel(modelId);\n  };\n  provider.specificationVersion = \"v4\";\n  provider.getAvailableModels = getAvailableModels;\n  provider.getCredits = getCredits;\n  provider.getSpendReport = getSpendReport;\n  provider.getGenerationInfo = getGenerationInfo;\n  provider.imageModel = (modelId) => {\n    return new GatewayImageModel(modelId, {\n      provider: \"gateway\",\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders()\n    });\n  };\n  provider.languageModel = createLanguageModel;\n  const createEmbeddingModel = (modelId) => {\n    return new GatewayEmbeddingModel(modelId, {\n      provider: \"gateway\",\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders()\n    });\n  };\n  provider.embeddingModel = createEmbeddingModel;\n  provider.textEmbeddingModel = createEmbeddingModel;\n  provider.videoModel = (modelId) => {\n    return new GatewayVideoModel(modelId, {\n      provider: \"gateway\",\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders()\n    });\n  };\n  const createRerankingModel = (modelId) => {\n    return new GatewayRerankingModel(modelId, {\n      provider: \"gateway\",\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders()\n    });\n  };\n  provider.rerankingModel = createRerankingModel;\n  provider.reranking = createRerankingModel;\n  const createSpeechModel = (modelId) => {\n    return new GatewaySpeechModel(modelId, {\n      provider: \"gateway\",\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders()\n    });\n  };\n  provider.speechModel = createSpeechModel;\n  provider.speech = createSpeechModel;\n  const createTranscriptionModel = (modelId) => {\n    return new GatewayTranscriptionModel(modelId, {\n      provider: \"gateway\",\n      baseURL,\n      headers: getHeaders,\n      fetch: options.fetch,\n      o11yHeaders: createO11yHeaders()\n    });\n  };\n  provider.transcriptionModel = createTranscriptionModel;\n  provider.transcription = createTranscriptionModel;\n  const createRealtimeModel = (modelId) => new GatewayRealtimeModel(modelId, {\n    provider: \"gateway.realtime\",\n    baseURL,\n    teamIdOrSlug: options.teamIdOrSlug,\n    createClientSecret: mintRealtimeClientSecret\n  });\n  provider.experimental_realtime = Object.assign(\n    (modelId) => createRealtimeModel(modelId),\n    {\n      getToken: async (tokenOptions) => {\n        const { model: modelId, ...secretOptions } = tokenOptions;\n        const model = createRealtimeModel(modelId);\n        const secret = await model.doCreateClientSecret(secretOptions);\n        return {\n          token: secret.token,\n          url: secret.url,\n          ...secret.expiresAt != null && { expiresAt: secret.expiresAt }\n        };\n      }\n    }\n  );\n  provider.chat = provider.languageModel;\n  provider.embedding = provider.embeddingModel;\n  provider.image = provider.imageModel;\n  provider.video = provider.videoModel;\n  provider.tools = gatewayTools;\n  return provider;\n}\nvar gateway = createGateway();\nasync function getGatewayAuthToken(options) {\n  const apiKey = loadOptionalSetting({\n    settingValue: options.apiKey,\n    environmentVariableName: \"AI_GATEWAY_API_KEY\"\n  });\n  if (apiKey) {\n    return {\n      token: apiKey,\n      authMethod: \"api-key\"\n    };\n  }\n  const oidcToken = await getVercelOidcToken();\n  return {\n    token: oidcToken,\n    authMethod: \"oidc\"\n  };\n}\nfunction assertGatewayRealtimeServerEnvironment() {\n  if (typeof globalThis.window !== \"undefined\") {\n    throw new Error(\n      \"AI Gateway realtime client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken() from your server and pass the returned token to the client.\"\n    );\n  }\n}\nexport {\n  GATEWAY_AUTH_SUBPROTOCOL_PREFIX,\n  GATEWAY_REALTIME_SUBPROTOCOL,\n  GATEWAY_TEAM_SUBPROTOCOL_PREFIX,\n  GatewayAuthenticationError,\n  GatewayError,\n  GatewayFailedDependencyError,\n  GatewayForbiddenError,\n  GatewayInternalServerError,\n  GatewayInvalidRequestError,\n  GatewayModelNotFoundError,\n  GatewayRateLimitError,\n  GatewayResponseError,\n  VERSION,\n  createGateway,\n  createGateway as createGatewayProvider,\n  gateway,\n  getGatewayRealtimeAuthToken,\n  getGatewayRealtimeProtocols,\n  getGatewayRealtimeTeamIdOrSlug\n};\n//# sourceMappingURL=index.js.map","const entityKind = Symbol.for(\"drizzle:entityKind\");\nconst hasOwnEntityKind = Symbol.for(\"drizzle:hasOwnEntityKind\");\nfunction is(value, type) {\n  if (!value || typeof value !== \"object\") {\n    return false;\n  }\n  if (value instanceof type) {\n    return true;\n  }\n  if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {\n    throw new Error(\n      `Class \"${type.name ?? \"<unknown>\"}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`\n    );\n  }\n  let cls = Object.getPrototypeOf(value).constructor;\n  if (cls) {\n    while (cls) {\n      if (entityKind in cls && cls[entityKind] === type[entityKind]) {\n        return true;\n      }\n      cls = Object.getPrototypeOf(cls);\n    }\n  }\n  return false;\n}\nexport {\n  entityKind,\n  hasOwnEntityKind,\n  is\n};\n//# sourceMappingURL=entity.js.map","import { entityKind } from \"./entity.js\";\nclass Column {\n  constructor(table, config) {\n    this.table = table;\n    this.config = config;\n    this.name = config.name;\n    this.keyAsName = config.keyAsName;\n    this.notNull = config.notNull;\n    this.default = config.default;\n    this.defaultFn = config.defaultFn;\n    this.onUpdateFn = config.onUpdateFn;\n    this.hasDefault = config.hasDefault;\n    this.primary = config.primaryKey;\n    this.isUnique = config.isUnique;\n    this.uniqueName = config.uniqueName;\n    this.uniqueType = config.uniqueType;\n    this.dataType = config.dataType;\n    this.columnType = config.columnType;\n    this.generated = config.generated;\n    this.generatedIdentity = config.generatedIdentity;\n  }\n  static [entityKind] = \"Column\";\n  name;\n  keyAsName;\n  primary;\n  notNull;\n  default;\n  defaultFn;\n  onUpdateFn;\n  hasDefault;\n  isUnique;\n  uniqueName;\n  uniqueType;\n  dataType;\n  columnType;\n  enumValues = void 0;\n  generated = void 0;\n  generatedIdentity = void 0;\n  config;\n  mapFromDriverValue(value) {\n    return value;\n  }\n  mapToDriverValue(value) {\n    return value;\n  }\n  // ** @internal */\n  shouldDisableInsert() {\n    return this.config.generated !== void 0 && this.config.generated.type !== \"byDefault\";\n  }\n}\nexport {\n  Column\n};\n//# sourceMappingURL=column.js.map","import { entityKind } from \"./entity.js\";\nclass ColumnBuilder {\n  static [entityKind] = \"ColumnBuilder\";\n  config;\n  constructor(name, dataType, columnType) {\n    this.config = {\n      name,\n      keyAsName: name === \"\",\n      notNull: false,\n      default: void 0,\n      hasDefault: false,\n      primaryKey: false,\n      isUnique: false,\n      uniqueName: void 0,\n      uniqueType: void 0,\n      dataType,\n      columnType,\n      generated: void 0\n    };\n  }\n  /**\n   * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.\n   *\n   * @example\n   * ```ts\n   * const users = pgTable('users', {\n   * \tid: integer('id').$type<UserId>().primaryKey(),\n   * \tdetails: json('details').$type<UserDetails>().notNull(),\n   * });\n   * ```\n   */\n  $type() {\n    return this;\n  }\n  /**\n   * Adds a `not null` clause to the column definition.\n   *\n   * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.\n   */\n  notNull() {\n    this.config.notNull = true;\n    return this;\n  }\n  /**\n   * Adds a `default <value>` clause to the column definition.\n   *\n   * Affects the `insert` model of the table - columns *with* `default` are optional on insert.\n   *\n   * If you need to set a dynamic default value, use {@link $defaultFn} instead.\n   */\n  default(value) {\n    this.config.default = value;\n    this.config.hasDefault = true;\n    return this;\n  }\n  /**\n   * Adds a dynamic default value to the column.\n   * The function will be called when the row is inserted, and the returned value will be used as the column value.\n   *\n   * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n   */\n  $defaultFn(fn) {\n    this.config.defaultFn = fn;\n    this.config.hasDefault = true;\n    return this;\n  }\n  /**\n   * Alias for {@link $defaultFn}.\n   */\n  $default = this.$defaultFn;\n  /**\n   * Adds a dynamic update value to the column.\n   * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.\n   * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.\n   *\n   * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n   */\n  $onUpdateFn(fn) {\n    this.config.onUpdateFn = fn;\n    this.config.hasDefault = true;\n    return this;\n  }\n  /**\n   * Alias for {@link $onUpdateFn}.\n   */\n  $onUpdate = this.$onUpdateFn;\n  /**\n   * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.\n   *\n   * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.\n   */\n  primaryKey() {\n    this.config.primaryKey = true;\n    this.config.notNull = true;\n    return this;\n  }\n  /** @internal Sets the name of the column to the key within the table definition if a name was not given. */\n  setName(name) {\n    if (this.config.name !== \"\") return;\n    this.config.name = name;\n  }\n}\nexport {\n  ColumnBuilder\n};\n//# sourceMappingURL=column-builder.js.map","const TableName = Symbol.for(\"drizzle:Name\");\nexport {\n  TableName\n};\n//# sourceMappingURL=table.utils.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nclass ForeignKeyBuilder {\n  static [entityKind] = \"PgForeignKeyBuilder\";\n  /** @internal */\n  reference;\n  /** @internal */\n  _onUpdate = \"no action\";\n  /** @internal */\n  _onDelete = \"no action\";\n  constructor(config, actions) {\n    this.reference = () => {\n      const { name, columns, foreignColumns } = config();\n      return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };\n    };\n    if (actions) {\n      this._onUpdate = actions.onUpdate;\n      this._onDelete = actions.onDelete;\n    }\n  }\n  onUpdate(action) {\n    this._onUpdate = action === void 0 ? \"no action\" : action;\n    return this;\n  }\n  onDelete(action) {\n    this._onDelete = action === void 0 ? \"no action\" : action;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new ForeignKey(table, this);\n  }\n}\nclass ForeignKey {\n  constructor(table, builder) {\n    this.table = table;\n    this.reference = builder.reference;\n    this.onUpdate = builder._onUpdate;\n    this.onDelete = builder._onDelete;\n  }\n  static [entityKind] = \"PgForeignKey\";\n  reference;\n  onUpdate;\n  onDelete;\n  getName() {\n    const { name, columns, foreignColumns } = this.reference();\n    const columnNames = columns.map((column) => column.name);\n    const foreignColumnNames = foreignColumns.map((column) => column.name);\n    const chunks = [\n      this.table[TableName],\n      ...columnNames,\n      foreignColumns[0].table[TableName],\n      ...foreignColumnNames\n    ];\n    return name ?? `${chunks.join(\"_\")}_fk`;\n  }\n}\nfunction foreignKey(config) {\n  function mappedConfig() {\n    const { name, columns, foreignColumns } = config;\n    return {\n      name,\n      columns,\n      foreignColumns\n    };\n  }\n  return new ForeignKeyBuilder(mappedConfig);\n}\nexport {\n  ForeignKey,\n  ForeignKeyBuilder,\n  foreignKey\n};\n//# sourceMappingURL=foreign-keys.js.map","function iife(fn, ...args) {\n  return fn(...args);\n}\nexport {\n  iife\n};\n//# sourceMappingURL=tracing-utils.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nfunction unique(name) {\n  return new UniqueOnConstraintBuilder(name);\n}\nfunction uniqueKeyName(table, columns) {\n  return `${table[TableName]}_${columns.join(\"_\")}_unique`;\n}\nclass UniqueConstraintBuilder {\n  constructor(columns, name) {\n    this.name = name;\n    this.columns = columns;\n  }\n  static [entityKind] = \"PgUniqueConstraintBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  nullsNotDistinctConfig = false;\n  nullsNotDistinct() {\n    this.nullsNotDistinctConfig = true;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);\n  }\n}\nclass UniqueOnConstraintBuilder {\n  static [entityKind] = \"PgUniqueOnConstraintBuilder\";\n  /** @internal */\n  name;\n  constructor(name) {\n    this.name = name;\n  }\n  on(...columns) {\n    return new UniqueConstraintBuilder(columns, this.name);\n  }\n}\nclass UniqueConstraint {\n  constructor(table, columns, nullsNotDistinct, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n    this.nullsNotDistinct = nullsNotDistinct;\n  }\n  static [entityKind] = \"PgUniqueConstraint\";\n  columns;\n  name;\n  nullsNotDistinct = false;\n  getName() {\n    return this.name;\n  }\n}\nexport {\n  UniqueConstraint,\n  UniqueConstraintBuilder,\n  UniqueOnConstraintBuilder,\n  unique,\n  uniqueKeyName\n};\n//# sourceMappingURL=unique-constraint.js.map","function parsePgArrayValue(arrayString, startFrom, inQuotes) {\n  for (let i = startFrom; i < arrayString.length; i++) {\n    const char = arrayString[i];\n    if (char === \"\\\\\") {\n      i++;\n      continue;\n    }\n    if (char === '\"') {\n      return [arrayString.slice(startFrom, i).replace(/\\\\/g, \"\"), i + 1];\n    }\n    if (inQuotes) {\n      continue;\n    }\n    if (char === \",\" || char === \"}\") {\n      return [arrayString.slice(startFrom, i).replace(/\\\\/g, \"\"), i];\n    }\n  }\n  return [arrayString.slice(startFrom).replace(/\\\\/g, \"\"), arrayString.length];\n}\nfunction parsePgNestedArray(arrayString, startFrom = 0) {\n  const result = [];\n  let i = startFrom;\n  let lastCharIsComma = false;\n  while (i < arrayString.length) {\n    const char = arrayString[i];\n    if (char === \",\") {\n      if (lastCharIsComma || i === startFrom) {\n        result.push(\"\");\n      }\n      lastCharIsComma = true;\n      i++;\n      continue;\n    }\n    lastCharIsComma = false;\n    if (char === \"\\\\\") {\n      i += 2;\n      continue;\n    }\n    if (char === '\"') {\n      const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);\n      result.push(value2);\n      i = startFrom2;\n      continue;\n    }\n    if (char === \"}\") {\n      return [result, i + 1];\n    }\n    if (char === \"{\") {\n      const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);\n      result.push(value2);\n      i = startFrom2;\n      continue;\n    }\n    const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);\n    result.push(value);\n    i = newStartFrom;\n  }\n  return [result, i];\n}\nfunction parsePgArray(arrayString) {\n  const [result] = parsePgNestedArray(arrayString, 1);\n  return result;\n}\nfunction makePgArray(array) {\n  return `{${array.map((item) => {\n    if (Array.isArray(item)) {\n      return makePgArray(item);\n    }\n    if (typeof item === \"string\") {\n      return `\"${item.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n    }\n    return `${item}`;\n  }).join(\",\")}}`;\n}\nexport {\n  makePgArray,\n  parsePgArray,\n  parsePgNestedArray\n};\n//# sourceMappingURL=array.js.map","import { ColumnBuilder } from \"../../column-builder.js\";\nimport { Column } from \"../../column.js\";\nimport { entityKind, is } from \"../../entity.js\";\nimport { ForeignKeyBuilder } from \"../foreign-keys.js\";\nimport { iife } from \"../../tracing-utils.js\";\nimport { uniqueKeyName } from \"../unique-constraint.js\";\nimport { makePgArray, parsePgArray } from \"../utils/array.js\";\nclass PgColumnBuilder extends ColumnBuilder {\n  foreignKeyConfigs = [];\n  static [entityKind] = \"PgColumnBuilder\";\n  array(size) {\n    return new PgArrayBuilder(this.config.name, this, size);\n  }\n  references(ref, actions = {}) {\n    this.foreignKeyConfigs.push({ ref, actions });\n    return this;\n  }\n  unique(name, config) {\n    this.config.isUnique = true;\n    this.config.uniqueName = name;\n    this.config.uniqueType = config?.nulls;\n    return this;\n  }\n  generatedAlwaysAs(as) {\n    this.config.generated = {\n      as,\n      type: \"always\",\n      mode: \"stored\"\n    };\n    return this;\n  }\n  /** @internal */\n  buildForeignKeys(column, table) {\n    return this.foreignKeyConfigs.map(({ ref, actions }) => {\n      return iife(\n        (ref2, actions2) => {\n          const builder = new ForeignKeyBuilder(() => {\n            const foreignColumn = ref2();\n            return { columns: [column], foreignColumns: [foreignColumn] };\n          });\n          if (actions2.onUpdate) {\n            builder.onUpdate(actions2.onUpdate);\n          }\n          if (actions2.onDelete) {\n            builder.onDelete(actions2.onDelete);\n          }\n          return builder.build(table);\n        },\n        ref,\n        actions\n      );\n    });\n  }\n  /** @internal */\n  buildExtraConfigColumn(table) {\n    return new ExtraConfigColumn(table, this.config);\n  }\n}\nclass PgColumn extends Column {\n  constructor(table, config) {\n    if (!config.uniqueName) {\n      config.uniqueName = uniqueKeyName(table, [config.name]);\n    }\n    super(table, config);\n    this.table = table;\n  }\n  static [entityKind] = \"PgColumn\";\n}\nclass ExtraConfigColumn extends PgColumn {\n  static [entityKind] = \"ExtraConfigColumn\";\n  getSQLType() {\n    return this.getSQLType();\n  }\n  indexConfig = {\n    order: this.config.order ?? \"asc\",\n    nulls: this.config.nulls ?? \"last\",\n    opClass: this.config.opClass\n  };\n  defaultConfig = {\n    order: \"asc\",\n    nulls: \"last\",\n    opClass: void 0\n  };\n  asc() {\n    this.indexConfig.order = \"asc\";\n    return this;\n  }\n  desc() {\n    this.indexConfig.order = \"desc\";\n    return this;\n  }\n  nullsFirst() {\n    this.indexConfig.nulls = \"first\";\n    return this;\n  }\n  nullsLast() {\n    this.indexConfig.nulls = \"last\";\n    return this;\n  }\n  /**\n   * ### PostgreSQL documentation quote\n   *\n   * > An operator class with optional parameters can be specified for each column of an index.\n   * The operator class identifies the operators to be used by the index for that column.\n   * For example, a B-tree index on four-byte integers would use the int4_ops class;\n   * this operator class includes comparison functions for four-byte integers.\n   * In practice the default operator class for the column's data type is usually sufficient.\n   * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.\n   * For example, we might want to sort a complex-number data type either by absolute value or by real part.\n   * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.\n   * More information about operator classes check:\n   *\n   * ### Useful links\n   * https://www.postgresql.org/docs/current/sql-createindex.html\n   *\n   * https://www.postgresql.org/docs/current/indexes-opclass.html\n   *\n   * https://www.postgresql.org/docs/current/xindex.html\n   *\n   * ### Additional types\n   * If you have the `pg_vector` extension installed in your database, you can use the\n   * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.\n   *\n   * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**\n   *\n   * @param opClass\n   * @returns\n   */\n  op(opClass) {\n    this.indexConfig.opClass = opClass;\n    return this;\n  }\n}\nclass IndexedColumn {\n  static [entityKind] = \"IndexedColumn\";\n  constructor(name, keyAsName, type, indexConfig) {\n    this.name = name;\n    this.keyAsName = keyAsName;\n    this.type = type;\n    this.indexConfig = indexConfig;\n  }\n  name;\n  keyAsName;\n  type;\n  indexConfig;\n}\nclass PgArrayBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgArrayBuilder\";\n  constructor(name, baseBuilder, size) {\n    super(name, \"array\", \"PgArray\");\n    this.config.baseBuilder = baseBuilder;\n    this.config.size = size;\n  }\n  /** @internal */\n  build(table) {\n    const baseColumn = this.config.baseBuilder.build(table);\n    return new PgArray(\n      table,\n      this.config,\n      baseColumn\n    );\n  }\n}\nclass PgArray extends PgColumn {\n  constructor(table, config, baseColumn, range) {\n    super(table, config);\n    this.baseColumn = baseColumn;\n    this.range = range;\n    this.size = config.size;\n  }\n  size;\n  static [entityKind] = \"PgArray\";\n  getSQLType() {\n    return `${this.baseColumn.getSQLType()}[${typeof this.size === \"number\" ? this.size : \"\"}]`;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      value = parsePgArray(value);\n    }\n    return value.map((v) => this.baseColumn.mapFromDriverValue(v));\n  }\n  mapToDriverValue(value, isNestedArray = false) {\n    const a = value.map(\n      (v) => v === null ? null : is(this.baseColumn, PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)\n    );\n    if (isNestedArray) return a;\n    return makePgArray(a);\n  }\n}\nexport {\n  ExtraConfigColumn,\n  IndexedColumn,\n  PgArray,\n  PgArrayBuilder,\n  PgColumn,\n  PgColumnBuilder\n};\n//# sourceMappingURL=common.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgEnumObjectColumnBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgEnumObjectColumnBuilder\";\n  constructor(name, enumInstance) {\n    super(name, \"string\", \"PgEnumObjectColumn\");\n    this.config.enum = enumInstance;\n  }\n  /** @internal */\n  build(table) {\n    return new PgEnumObjectColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass PgEnumObjectColumn extends PgColumn {\n  static [entityKind] = \"PgEnumObjectColumn\";\n  enum;\n  enumValues = this.config.enum.enumValues;\n  constructor(table, config) {\n    super(table, config);\n    this.enum = config.enum;\n  }\n  getSQLType() {\n    return this.enum.enumName;\n  }\n}\nconst isPgEnumSym = Symbol.for(\"drizzle:isPgEnum\");\nfunction isPgEnum(obj) {\n  return !!obj && typeof obj === \"function\" && isPgEnumSym in obj && obj[isPgEnumSym] === true;\n}\nclass PgEnumColumnBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgEnumColumnBuilder\";\n  constructor(name, enumInstance) {\n    super(name, \"string\", \"PgEnumColumn\");\n    this.config.enum = enumInstance;\n  }\n  /** @internal */\n  build(table) {\n    return new PgEnumColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass PgEnumColumn extends PgColumn {\n  static [entityKind] = \"PgEnumColumn\";\n  enum = this.config.enum;\n  enumValues = this.config.enum.enumValues;\n  constructor(table, config) {\n    super(table, config);\n    this.enum = config.enum;\n  }\n  getSQLType() {\n    return this.enum.enumName;\n  }\n}\nfunction pgEnum(enumName, input) {\n  return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0);\n}\nfunction pgEnumWithSchema(enumName, values, schema) {\n  const enumInstance = Object.assign(\n    (name) => new PgEnumColumnBuilder(name ?? \"\", enumInstance),\n    {\n      enumName,\n      enumValues: values,\n      schema,\n      [isPgEnumSym]: true\n    }\n  );\n  return enumInstance;\n}\nfunction pgEnumObjectWithSchema(enumName, values, schema) {\n  const enumInstance = Object.assign(\n    (name) => new PgEnumObjectColumnBuilder(name ?? \"\", enumInstance),\n    {\n      enumName,\n      enumValues: Object.values(values),\n      schema,\n      [isPgEnumSym]: true\n    }\n  );\n  return enumInstance;\n}\nexport {\n  PgEnumColumn,\n  PgEnumColumnBuilder,\n  PgEnumObjectColumn,\n  PgEnumObjectColumnBuilder,\n  isPgEnum,\n  pgEnum,\n  pgEnumObjectWithSchema,\n  pgEnumWithSchema\n};\n//# sourceMappingURL=enum.js.map","import { entityKind } from \"./entity.js\";\nclass Subquery {\n  static [entityKind] = \"Subquery\";\n  constructor(sql, fields, alias, isWith = false, usedTables = []) {\n    this._ = {\n      brand: \"Subquery\",\n      sql,\n      selectedFields: fields,\n      alias,\n      isWith,\n      usedTables\n    };\n  }\n  // getSQL(): SQL<unknown> {\n  // \treturn new SQL([this]);\n  // }\n}\nclass WithSubquery extends Subquery {\n  static [entityKind] = \"WithSubquery\";\n}\nexport {\n  Subquery,\n  WithSubquery\n};\n//# sourceMappingURL=subquery.js.map","import { iife } from \"./tracing-utils.js\";\nimport { npmVersion } from \"./version.js\";\nlet otel;\nlet rawTracer;\nconst tracer = {\n  startActiveSpan(name, fn) {\n    if (!otel) {\n      return fn();\n    }\n    if (!rawTracer) {\n      rawTracer = otel.trace.getTracer(\"drizzle-orm\", npmVersion);\n    }\n    return iife(\n      (otel2, rawTracer2) => rawTracer2.startActiveSpan(\n        name,\n        (span) => {\n          try {\n            return fn(span);\n          } catch (e) {\n            span.setStatus({\n              code: otel2.SpanStatusCode.ERROR,\n              message: e instanceof Error ? e.message : \"Unknown error\"\n              // eslint-disable-line no-instanceof/no-instanceof\n            });\n            throw e;\n          } finally {\n            span.end();\n          }\n        }\n      ),\n      otel,\n      rawTracer\n    );\n  }\n};\nexport {\n  tracer\n};\n//# sourceMappingURL=tracing.js.map","const ViewBaseConfig = Symbol.for(\"drizzle:ViewBaseConfig\");\nexport {\n  ViewBaseConfig\n};\n//# sourceMappingURL=view-common.js.map","import { entityKind } from \"./entity.js\";\nimport { TableName } from \"./table.utils.js\";\nconst Schema = Symbol.for(\"drizzle:Schema\");\nconst Columns = Symbol.for(\"drizzle:Columns\");\nconst ExtraConfigColumns = Symbol.for(\"drizzle:ExtraConfigColumns\");\nconst OriginalName = Symbol.for(\"drizzle:OriginalName\");\nconst BaseName = Symbol.for(\"drizzle:BaseName\");\nconst IsAlias = Symbol.for(\"drizzle:IsAlias\");\nconst ExtraConfigBuilder = Symbol.for(\"drizzle:ExtraConfigBuilder\");\nconst IsDrizzleTable = Symbol.for(\"drizzle:IsDrizzleTable\");\nclass Table {\n  static [entityKind] = \"Table\";\n  /** @internal */\n  static Symbol = {\n    Name: TableName,\n    Schema,\n    OriginalName,\n    Columns,\n    ExtraConfigColumns,\n    BaseName,\n    IsAlias,\n    ExtraConfigBuilder\n  };\n  /**\n   * @internal\n   * Can be changed if the table is aliased.\n   */\n  [TableName];\n  /**\n   * @internal\n   * Used to store the original name of the table, before any aliasing.\n   */\n  [OriginalName];\n  /** @internal */\n  [Schema];\n  /** @internal */\n  [Columns];\n  /** @internal */\n  [ExtraConfigColumns];\n  /**\n   *  @internal\n   * Used to store the table name before the transformation via the `tableCreator` functions.\n   */\n  [BaseName];\n  /** @internal */\n  [IsAlias] = false;\n  /** @internal */\n  [IsDrizzleTable] = true;\n  /** @internal */\n  [ExtraConfigBuilder] = void 0;\n  constructor(name, schema, baseName) {\n    this[TableName] = this[OriginalName] = name;\n    this[Schema] = schema;\n    this[BaseName] = baseName;\n  }\n}\nfunction isTable(table) {\n  return typeof table === \"object\" && table !== null && IsDrizzleTable in table;\n}\nfunction getTableName(table) {\n  return table[TableName];\n}\nfunction getTableUniqueName(table) {\n  return `${table[Schema] ?? \"public\"}.${table[TableName]}`;\n}\nexport {\n  BaseName,\n  Columns,\n  ExtraConfigBuilder,\n  ExtraConfigColumns,\n  IsAlias,\n  OriginalName,\n  Schema,\n  Table,\n  getTableName,\n  getTableUniqueName,\n  isTable\n};\n//# sourceMappingURL=table.js.map","import { entityKind, is } from \"../entity.js\";\nimport { isPgEnum } from \"../pg-core/columns/enum.js\";\nimport { Subquery } from \"../subquery.js\";\nimport { tracer } from \"../tracing.js\";\nimport { ViewBaseConfig } from \"../view-common.js\";\nimport { Column } from \"../column.js\";\nimport { IsAlias, Table } from \"../table.js\";\nclass FakePrimitiveParam {\n  static [entityKind] = \"FakePrimitiveParam\";\n}\nfunction isSQLWrapper(value) {\n  return value !== null && value !== void 0 && typeof value.getSQL === \"function\";\n}\nfunction mergeQueries(queries) {\n  const result = { sql: \"\", params: [] };\n  for (const query of queries) {\n    result.sql += query.sql;\n    result.params.push(...query.params);\n    if (query.typings?.length) {\n      if (!result.typings) {\n        result.typings = [];\n      }\n      result.typings.push(...query.typings);\n    }\n  }\n  return result;\n}\nclass StringChunk {\n  static [entityKind] = \"StringChunk\";\n  value;\n  constructor(value) {\n    this.value = Array.isArray(value) ? value : [value];\n  }\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nclass SQL {\n  constructor(queryChunks) {\n    this.queryChunks = queryChunks;\n    for (const chunk of queryChunks) {\n      if (is(chunk, Table)) {\n        const schemaName = chunk[Table.Symbol.Schema];\n        this.usedTables.push(\n          schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + \".\" + chunk[Table.Symbol.Name]\n        );\n      }\n    }\n  }\n  static [entityKind] = \"SQL\";\n  /** @internal */\n  decoder = noopDecoder;\n  shouldInlineParams = false;\n  /** @internal */\n  usedTables = [];\n  append(query) {\n    this.queryChunks.push(...query.queryChunks);\n    return this;\n  }\n  toQuery(config) {\n    return tracer.startActiveSpan(\"drizzle.buildSQL\", (span) => {\n      const query = this.buildQueryFromSourceParams(this.queryChunks, config);\n      span?.setAttributes({\n        \"drizzle.query.text\": query.sql,\n        \"drizzle.query.params\": JSON.stringify(query.params)\n      });\n      return query;\n    });\n  }\n  buildQueryFromSourceParams(chunks, _config) {\n    const config = Object.assign({}, _config, {\n      inlineParams: _config.inlineParams || this.shouldInlineParams,\n      paramStartIndex: _config.paramStartIndex || { value: 0 }\n    });\n    const {\n      casing,\n      escapeName,\n      escapeParam,\n      prepareTyping,\n      inlineParams,\n      paramStartIndex\n    } = config;\n    return mergeQueries(chunks.map((chunk) => {\n      if (is(chunk, StringChunk)) {\n        return { sql: chunk.value.join(\"\"), params: [] };\n      }\n      if (is(chunk, Name)) {\n        return { sql: escapeName(chunk.value), params: [] };\n      }\n      if (chunk === void 0) {\n        return { sql: \"\", params: [] };\n      }\n      if (Array.isArray(chunk)) {\n        const result = [new StringChunk(\"(\")];\n        for (const [i, p] of chunk.entries()) {\n          result.push(p);\n          if (i < chunk.length - 1) {\n            result.push(new StringChunk(\", \"));\n          }\n        }\n        result.push(new StringChunk(\")\"));\n        return this.buildQueryFromSourceParams(result, config);\n      }\n      if (is(chunk, SQL)) {\n        return this.buildQueryFromSourceParams(chunk.queryChunks, {\n          ...config,\n          inlineParams: inlineParams || chunk.shouldInlineParams\n        });\n      }\n      if (is(chunk, Table)) {\n        const schemaName = chunk[Table.Symbol.Schema];\n        const tableName = chunk[Table.Symbol.Name];\n        return {\n          sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + \".\" + escapeName(tableName),\n          params: []\n        };\n      }\n      if (is(chunk, Column)) {\n        const columnName = casing.getColumnCasing(chunk);\n        if (_config.invokeSource === \"indexes\") {\n          return { sql: escapeName(columnName), params: [] };\n        }\n        const schemaName = chunk.table[Table.Symbol.Schema];\n        return {\n          sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + \".\" + escapeName(columnName) : escapeName(schemaName) + \".\" + escapeName(chunk.table[Table.Symbol.Name]) + \".\" + escapeName(columnName),\n          params: []\n        };\n      }\n      if (is(chunk, View)) {\n        const schemaName = chunk[ViewBaseConfig].schema;\n        const viewName = chunk[ViewBaseConfig].name;\n        return {\n          sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + \".\" + escapeName(viewName),\n          params: []\n        };\n      }\n      if (is(chunk, Param)) {\n        if (is(chunk.value, Placeholder)) {\n          return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: [\"none\"] };\n        }\n        const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);\n        if (is(mappedValue, SQL)) {\n          return this.buildQueryFromSourceParams([mappedValue], config);\n        }\n        if (inlineParams) {\n          return { sql: this.mapInlineParam(mappedValue, config), params: [] };\n        }\n        let typings = [\"none\"];\n        if (prepareTyping) {\n          typings = [prepareTyping(chunk.encoder)];\n        }\n        return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };\n      }\n      if (is(chunk, Placeholder)) {\n        return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: [\"none\"] };\n      }\n      if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== void 0) {\n        return { sql: escapeName(chunk.fieldAlias), params: [] };\n      }\n      if (is(chunk, Subquery)) {\n        if (chunk._.isWith) {\n          return { sql: escapeName(chunk._.alias), params: [] };\n        }\n        return this.buildQueryFromSourceParams([\n          new StringChunk(\"(\"),\n          chunk._.sql,\n          new StringChunk(\") \"),\n          new Name(chunk._.alias)\n        ], config);\n      }\n      if (isPgEnum(chunk)) {\n        if (chunk.schema) {\n          return { sql: escapeName(chunk.schema) + \".\" + escapeName(chunk.enumName), params: [] };\n        }\n        return { sql: escapeName(chunk.enumName), params: [] };\n      }\n      if (isSQLWrapper(chunk)) {\n        if (chunk.shouldOmitSQLParens?.()) {\n          return this.buildQueryFromSourceParams([chunk.getSQL()], config);\n        }\n        return this.buildQueryFromSourceParams([\n          new StringChunk(\"(\"),\n          chunk.getSQL(),\n          new StringChunk(\")\")\n        ], config);\n      }\n      if (inlineParams) {\n        return { sql: this.mapInlineParam(chunk, config), params: [] };\n      }\n      return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: [\"none\"] };\n    }));\n  }\n  mapInlineParam(chunk, { escapeString }) {\n    if (chunk === null) {\n      return \"null\";\n    }\n    if (typeof chunk === \"number\" || typeof chunk === \"boolean\") {\n      return chunk.toString();\n    }\n    if (typeof chunk === \"string\") {\n      return escapeString(chunk);\n    }\n    if (typeof chunk === \"object\") {\n      const mappedValueAsString = chunk.toString();\n      if (mappedValueAsString === \"[object Object]\") {\n        return escapeString(JSON.stringify(chunk));\n      }\n      return escapeString(mappedValueAsString);\n    }\n    throw new Error(\"Unexpected param value: \" + chunk);\n  }\n  getSQL() {\n    return this;\n  }\n  as(alias) {\n    if (alias === void 0) {\n      return this;\n    }\n    return new SQL.Aliased(this, alias);\n  }\n  mapWith(decoder) {\n    this.decoder = typeof decoder === \"function\" ? { mapFromDriverValue: decoder } : decoder;\n    return this;\n  }\n  inlineParams() {\n    this.shouldInlineParams = true;\n    return this;\n  }\n  /**\n   * This method is used to conditionally include a part of the query.\n   *\n   * @param condition - Condition to check\n   * @returns itself if the condition is `true`, otherwise `undefined`\n   */\n  if(condition) {\n    return condition ? this : void 0;\n  }\n}\nclass Name {\n  constructor(value) {\n    this.value = value;\n  }\n  static [entityKind] = \"Name\";\n  brand;\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction name(value) {\n  return new Name(value);\n}\nfunction isDriverValueEncoder(value) {\n  return typeof value === \"object\" && value !== null && \"mapToDriverValue\" in value && typeof value.mapToDriverValue === \"function\";\n}\nconst noopDecoder = {\n  mapFromDriverValue: (value) => value\n};\nconst noopEncoder = {\n  mapToDriverValue: (value) => value\n};\nconst noopMapper = {\n  ...noopDecoder,\n  ...noopEncoder\n};\nclass Param {\n  /**\n   * @param value - Parameter value\n   * @param encoder - Encoder to convert the value to a driver parameter\n   */\n  constructor(value, encoder = noopEncoder) {\n    this.value = value;\n    this.encoder = encoder;\n  }\n  static [entityKind] = \"Param\";\n  brand;\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction param(value, encoder) {\n  return new Param(value, encoder);\n}\nfunction sql(strings, ...params) {\n  const queryChunks = [];\n  if (params.length > 0 || strings.length > 0 && strings[0] !== \"\") {\n    queryChunks.push(new StringChunk(strings[0]));\n  }\n  for (const [paramIndex, param2] of params.entries()) {\n    queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));\n  }\n  return new SQL(queryChunks);\n}\n((sql2) => {\n  function empty() {\n    return new SQL([]);\n  }\n  sql2.empty = empty;\n  function fromList(list) {\n    return new SQL(list);\n  }\n  sql2.fromList = fromList;\n  function raw(str) {\n    return new SQL([new StringChunk(str)]);\n  }\n  sql2.raw = raw;\n  function join(chunks, separator) {\n    const result = [];\n    for (const [i, chunk] of chunks.entries()) {\n      if (i > 0 && separator !== void 0) {\n        result.push(separator);\n      }\n      result.push(chunk);\n    }\n    return new SQL(result);\n  }\n  sql2.join = join;\n  function identifier(value) {\n    return new Name(value);\n  }\n  sql2.identifier = identifier;\n  function placeholder2(name2) {\n    return new Placeholder(name2);\n  }\n  sql2.placeholder = placeholder2;\n  function param2(value, encoder) {\n    return new Param(value, encoder);\n  }\n  sql2.param = param2;\n})(sql || (sql = {}));\n((SQL2) => {\n  class Aliased {\n    constructor(sql2, fieldAlias) {\n      this.sql = sql2;\n      this.fieldAlias = fieldAlias;\n    }\n    static [entityKind] = \"SQL.Aliased\";\n    /** @internal */\n    isSelectionField = false;\n    getSQL() {\n      return this.sql;\n    }\n    /** @internal */\n    clone() {\n      return new Aliased(this.sql, this.fieldAlias);\n    }\n  }\n  SQL2.Aliased = Aliased;\n})(SQL || (SQL = {}));\nclass Placeholder {\n  constructor(name2) {\n    this.name = name2;\n  }\n  static [entityKind] = \"Placeholder\";\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction placeholder(name2) {\n  return new Placeholder(name2);\n}\nfunction fillPlaceholders(params, values) {\n  return params.map((p) => {\n    if (is(p, Placeholder)) {\n      if (!(p.name in values)) {\n        throw new Error(`No value for placeholder \"${p.name}\" was provided`);\n      }\n      return values[p.name];\n    }\n    if (is(p, Param) && is(p.value, Placeholder)) {\n      if (!(p.value.name in values)) {\n        throw new Error(`No value for placeholder \"${p.value.name}\" was provided`);\n      }\n      return p.encoder.mapToDriverValue(values[p.value.name]);\n    }\n    return p;\n  });\n}\nconst IsDrizzleView = Symbol.for(\"drizzle:IsDrizzleView\");\nclass View {\n  static [entityKind] = \"View\";\n  /** @internal */\n  [ViewBaseConfig];\n  /** @internal */\n  [IsDrizzleView] = true;\n  constructor({ name: name2, schema, selectedFields, query }) {\n    this[ViewBaseConfig] = {\n      name: name2,\n      originalName: name2,\n      schema,\n      selectedFields,\n      query,\n      isExisting: !query,\n      isAlias: false\n    };\n  }\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction isView(view) {\n  return typeof view === \"object\" && view !== null && IsDrizzleView in view;\n}\nfunction getViewName(view) {\n  return view[ViewBaseConfig].name;\n}\nColumn.prototype.getSQL = function() {\n  return new SQL([this]);\n};\nTable.prototype.getSQL = function() {\n  return new SQL([this]);\n};\nSubquery.prototype.getSQL = function() {\n  return new SQL([this]);\n};\nexport {\n  FakePrimitiveParam,\n  Name,\n  Param,\n  Placeholder,\n  SQL,\n  StringChunk,\n  View,\n  fillPlaceholders,\n  getViewName,\n  isDriverValueEncoder,\n  isSQLWrapper,\n  isView,\n  name,\n  noopDecoder,\n  noopEncoder,\n  noopMapper,\n  param,\n  placeholder,\n  sql\n};\n//# sourceMappingURL=sql.js.map","import { Column } from \"./column.js\";\nimport { is } from \"./entity.js\";\nimport { Param, SQL, View } from \"./sql/sql.js\";\nimport { Subquery } from \"./subquery.js\";\nimport { getTableName, Table } from \"./table.js\";\nimport { ViewBaseConfig } from \"./view-common.js\";\nfunction mapResultRow(columns, row, joinsNotNullableMap) {\n  const nullifyMap = {};\n  const result = columns.reduce(\n    (result2, { path, field }, columnIndex) => {\n      let decoder;\n      if (is(field, Column)) {\n        decoder = field;\n      } else if (is(field, SQL)) {\n        decoder = field.decoder;\n      } else if (is(field, Subquery)) {\n        decoder = field._.sql.decoder;\n      } else {\n        decoder = field.sql.decoder;\n      }\n      let node = result2;\n      for (const [pathChunkIndex, pathChunk] of path.entries()) {\n        if (pathChunkIndex < path.length - 1) {\n          if (!(pathChunk in node)) {\n            node[pathChunk] = {};\n          }\n          node = node[pathChunk];\n        } else {\n          const rawValue = row[columnIndex];\n          const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);\n          if (joinsNotNullableMap && is(field, Column) && path.length === 2) {\n            const objectName = path[0];\n            if (!(objectName in nullifyMap)) {\n              nullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n            } else if (typeof nullifyMap[objectName] === \"string\" && nullifyMap[objectName] !== getTableName(field.table)) {\n              nullifyMap[objectName] = false;\n            }\n          }\n        }\n      }\n      return result2;\n    },\n    {}\n  );\n  if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n    for (const [objectName, tableName] of Object.entries(nullifyMap)) {\n      if (typeof tableName === \"string\" && !joinsNotNullableMap[tableName]) {\n        result[objectName] = null;\n      }\n    }\n  }\n  return result;\n}\nfunction orderSelectedFields(fields, pathPrefix) {\n  return Object.entries(fields).reduce((result, [name, field]) => {\n    if (typeof name !== \"string\") {\n      return result;\n    }\n    const newPath = pathPrefix ? [...pathPrefix, name] : [name];\n    if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {\n      result.push({ path: newPath, field });\n    } else if (is(field, Table)) {\n      result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));\n    } else {\n      result.push(...orderSelectedFields(field, newPath));\n    }\n    return result;\n  }, []);\n}\nfunction haveSameKeys(left, right) {\n  const leftKeys = Object.keys(left);\n  const rightKeys = Object.keys(right);\n  if (leftKeys.length !== rightKeys.length) {\n    return false;\n  }\n  for (const [index, key] of leftKeys.entries()) {\n    if (key !== rightKeys[index]) {\n      return false;\n    }\n  }\n  return true;\n}\nfunction mapUpdateSet(table, values) {\n  const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {\n    if (is(value, SQL) || is(value, Column)) {\n      return [key, value];\n    } else {\n      return [key, new Param(value, table[Table.Symbol.Columns][key])];\n    }\n  });\n  if (entries.length === 0) {\n    throw new Error(\"No values to set\");\n  }\n  return Object.fromEntries(entries);\n}\nfunction applyMixins(baseClass, extendedClasses) {\n  for (const extendedClass of extendedClasses) {\n    for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {\n      if (name === \"constructor\") continue;\n      Object.defineProperty(\n        baseClass.prototype,\n        name,\n        Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null)\n      );\n    }\n  }\n}\nfunction getTableColumns(table) {\n  return table[Table.Symbol.Columns];\n}\nfunction getViewSelectedFields(view) {\n  return view[ViewBaseConfig].selectedFields;\n}\nfunction getTableLikeName(table) {\n  return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];\n}\nfunction getColumnNameAndConfig(a, b) {\n  return {\n    name: typeof a === \"string\" && a.length > 0 ? a : \"\",\n    config: typeof a === \"object\" ? a : b\n  };\n}\nconst _ = {};\nconst __ = {};\nfunction isConfig(data) {\n  if (typeof data !== \"object\" || data === null) return false;\n  if (data.constructor.name !== \"Object\") return false;\n  if (\"logger\" in data) {\n    const type = typeof data[\"logger\"];\n    if (type !== \"boolean\" && (type !== \"object\" || typeof data[\"logger\"][\"logQuery\"] !== \"function\") && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"schema\" in data) {\n    const type = typeof data[\"schema\"];\n    if (type !== \"object\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"casing\" in data) {\n    const type = typeof data[\"casing\"];\n    if (type !== \"string\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"mode\" in data) {\n    if (data[\"mode\"] !== \"default\" || data[\"mode\"] !== \"planetscale\" || data[\"mode\"] !== void 0) return false;\n    return true;\n  }\n  if (\"connection\" in data) {\n    const type = typeof data[\"connection\"];\n    if (type !== \"string\" && type !== \"object\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"client\" in data) {\n    const type = typeof data[\"client\"];\n    if (type !== \"object\" && type !== \"function\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (Object.keys(data).length === 0) return true;\n  return false;\n}\nconst textDecoder = typeof TextDecoder === \"undefined\" ? null : new TextDecoder();\nexport {\n  applyMixins,\n  getColumnNameAndConfig,\n  getTableColumns,\n  getTableLikeName,\n  getViewSelectedFields,\n  haveSameKeys,\n  isConfig,\n  mapResultRow,\n  mapUpdateSet,\n  orderSelectedFields,\n  textDecoder\n};\n//# sourceMappingURL=utils.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumnBuilder } from \"./common.js\";\nclass PgIntColumnBaseBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgIntColumnBaseBuilder\";\n  generatedAlwaysAsIdentity(sequence) {\n    if (sequence) {\n      const { name, ...options } = sequence;\n      this.config.generatedIdentity = {\n        type: \"always\",\n        sequenceName: name,\n        sequenceOptions: options\n      };\n    } else {\n      this.config.generatedIdentity = {\n        type: \"always\"\n      };\n    }\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n    return this;\n  }\n  generatedByDefaultAsIdentity(sequence) {\n    if (sequence) {\n      const { name, ...options } = sequence;\n      this.config.generatedIdentity = {\n        type: \"byDefault\",\n        sequenceName: name,\n        sequenceOptions: options\n      };\n    } else {\n      this.config.generatedIdentity = {\n        type: \"byDefault\"\n      };\n    }\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n    return this;\n  }\n}\nexport {\n  PgIntColumnBaseBuilder\n};\n//# sourceMappingURL=int.common.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgIntColumnBaseBuilder } from \"./int.common.js\";\nclass PgBigInt53Builder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgBigInt53Builder\";\n  constructor(name) {\n    super(name, \"number\", \"PgBigInt53\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigInt53(table, this.config);\n  }\n}\nclass PgBigInt53 extends PgColumn {\n  static [entityKind] = \"PgBigInt53\";\n  getSQLType() {\n    return \"bigint\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") {\n      return value;\n    }\n    return Number(value);\n  }\n}\nclass PgBigInt64Builder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgBigInt64Builder\";\n  constructor(name) {\n    super(name, \"bigint\", \"PgBigInt64\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigInt64(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBigInt64 extends PgColumn {\n  static [entityKind] = \"PgBigInt64\";\n  getSQLType() {\n    return \"bigint\";\n  }\n  // eslint-disable-next-line unicorn/prefer-native-coercion-functions\n  mapFromDriverValue(value) {\n    return BigInt(value);\n  }\n}\nfunction bigint(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config.mode === \"number\") {\n    return new PgBigInt53Builder(name);\n  }\n  return new PgBigInt64Builder(name);\n}\nexport {\n  PgBigInt53,\n  PgBigInt53Builder,\n  PgBigInt64,\n  PgBigInt64Builder,\n  bigint\n};\n//# sourceMappingURL=bigint.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgBigSerial53Builder extends PgColumnBuilder {\n  static [entityKind] = \"PgBigSerial53Builder\";\n  constructor(name) {\n    super(name, \"number\", \"PgBigSerial53\");\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigSerial53(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBigSerial53 extends PgColumn {\n  static [entityKind] = \"PgBigSerial53\";\n  getSQLType() {\n    return \"bigserial\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") {\n      return value;\n    }\n    return Number(value);\n  }\n}\nclass PgBigSerial64Builder extends PgColumnBuilder {\n  static [entityKind] = \"PgBigSerial64Builder\";\n  constructor(name) {\n    super(name, \"bigint\", \"PgBigSerial64\");\n    this.config.hasDefault = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigSerial64(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBigSerial64 extends PgColumn {\n  static [entityKind] = \"PgBigSerial64\";\n  getSQLType() {\n    return \"bigserial\";\n  }\n  // eslint-disable-next-line unicorn/prefer-native-coercion-functions\n  mapFromDriverValue(value) {\n    return BigInt(value);\n  }\n}\nfunction bigserial(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config.mode === \"number\") {\n    return new PgBigSerial53Builder(name);\n  }\n  return new PgBigSerial64Builder(name);\n}\nexport {\n  PgBigSerial53,\n  PgBigSerial53Builder,\n  PgBigSerial64,\n  PgBigSerial64Builder,\n  bigserial\n};\n//# sourceMappingURL=bigserial.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgBooleanBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgBooleanBuilder\";\n  constructor(name) {\n    super(name, \"boolean\", \"PgBoolean\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgBoolean(table, this.config);\n  }\n}\nclass PgBoolean extends PgColumn {\n  static [entityKind] = \"PgBoolean\";\n  getSQLType() {\n    return \"boolean\";\n  }\n}\nfunction boolean(name) {\n  return new PgBooleanBuilder(name ?? \"\");\n}\nexport {\n  PgBoolean,\n  PgBooleanBuilder,\n  boolean\n};\n//# sourceMappingURL=boolean.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgCharBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgCharBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgChar\");\n    this.config.length = config.length;\n    this.config.enumValues = config.enum;\n  }\n  /** @internal */\n  build(table) {\n    return new PgChar(\n      table,\n      this.config\n    );\n  }\n}\nclass PgChar extends PgColumn {\n  static [entityKind] = \"PgChar\";\n  length = this.config.length;\n  enumValues = this.config.enumValues;\n  getSQLType() {\n    return this.length === void 0 ? `char` : `char(${this.length})`;\n  }\n}\nfunction char(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgCharBuilder(name, config);\n}\nexport {\n  PgChar,\n  PgCharBuilder,\n  char\n};\n//# sourceMappingURL=char.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgCidrBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgCidrBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgCidr\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgCidr(table, this.config);\n  }\n}\nclass PgCidr extends PgColumn {\n  static [entityKind] = \"PgCidr\";\n  getSQLType() {\n    return \"cidr\";\n  }\n}\nfunction cidr(name) {\n  return new PgCidrBuilder(name ?? \"\");\n}\nexport {\n  PgCidr,\n  PgCidrBuilder,\n  cidr\n};\n//# sourceMappingURL=cidr.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgCustomColumnBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgCustomColumnBuilder\";\n  constructor(name, fieldConfig, customTypeParams) {\n    super(name, \"custom\", \"PgCustomColumn\");\n    this.config.fieldConfig = fieldConfig;\n    this.config.customTypeParams = customTypeParams;\n  }\n  /** @internal */\n  build(table) {\n    return new PgCustomColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass PgCustomColumn extends PgColumn {\n  static [entityKind] = \"PgCustomColumn\";\n  sqlName;\n  mapTo;\n  mapFrom;\n  constructor(table, config) {\n    super(table, config);\n    this.sqlName = config.customTypeParams.dataType(config.fieldConfig);\n    this.mapTo = config.customTypeParams.toDriver;\n    this.mapFrom = config.customTypeParams.fromDriver;\n  }\n  getSQLType() {\n    return this.sqlName;\n  }\n  mapFromDriverValue(value) {\n    return typeof this.mapFrom === \"function\" ? this.mapFrom(value) : value;\n  }\n  mapToDriverValue(value) {\n    return typeof this.mapTo === \"function\" ? this.mapTo(value) : value;\n  }\n}\nfunction customType(customTypeParams) {\n  return (a, b) => {\n    const { name, config } = getColumnNameAndConfig(a, b);\n    return new PgCustomColumnBuilder(name, config, customTypeParams);\n  };\n}\nexport {\n  PgCustomColumn,\n  PgCustomColumnBuilder,\n  customType\n};\n//# sourceMappingURL=custom.js.map","import { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { PgColumnBuilder } from \"./common.js\";\nclass PgDateColumnBaseBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgDateColumnBaseBuilder\";\n  defaultNow() {\n    return this.default(sql`now()`);\n  }\n}\nexport {\n  PgDateColumnBaseBuilder\n};\n//# sourceMappingURL=date.common.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgDateColumnBaseBuilder } from \"./date.common.js\";\nclass PgDateBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgDateBuilder\";\n  constructor(name) {\n    super(name, \"date\", \"PgDate\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgDate(table, this.config);\n  }\n}\nclass PgDate extends PgColumn {\n  static [entityKind] = \"PgDate\";\n  getSQLType() {\n    return \"date\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return new Date(value);\n    return value;\n  }\n  mapToDriverValue(value) {\n    return value.toISOString();\n  }\n}\nclass PgDateStringBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgDateStringBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgDateString\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgDateString(\n      table,\n      this.config\n    );\n  }\n}\nclass PgDateString extends PgColumn {\n  static [entityKind] = \"PgDateString\";\n  getSQLType() {\n    return \"date\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    return value.toISOString().slice(0, -14);\n  }\n}\nfunction date(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"date\") {\n    return new PgDateBuilder(name);\n  }\n  return new PgDateStringBuilder(name);\n}\nexport {\n  PgDate,\n  PgDateBuilder,\n  PgDateString,\n  PgDateStringBuilder,\n  date\n};\n//# sourceMappingURL=date.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgDoublePrecisionBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgDoublePrecisionBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgDoublePrecision\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgDoublePrecision(\n      table,\n      this.config\n    );\n  }\n}\nclass PgDoublePrecision extends PgColumn {\n  static [entityKind] = \"PgDoublePrecision\";\n  getSQLType() {\n    return \"double precision\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      return Number.parseFloat(value);\n    }\n    return value;\n  }\n}\nfunction doublePrecision(name) {\n  return new PgDoublePrecisionBuilder(name ?? \"\");\n}\nexport {\n  PgDoublePrecision,\n  PgDoublePrecisionBuilder,\n  doublePrecision\n};\n//# sourceMappingURL=double-precision.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgInetBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgInetBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgInet\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgInet(table, this.config);\n  }\n}\nclass PgInet extends PgColumn {\n  static [entityKind] = \"PgInet\";\n  getSQLType() {\n    return \"inet\";\n  }\n}\nfunction inet(name) {\n  return new PgInetBuilder(name ?? \"\");\n}\nexport {\n  PgInet,\n  PgInetBuilder,\n  inet\n};\n//# sourceMappingURL=inet.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgIntColumnBaseBuilder } from \"./int.common.js\";\nclass PgIntegerBuilder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgIntegerBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgInteger\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgInteger(table, this.config);\n  }\n}\nclass PgInteger extends PgColumn {\n  static [entityKind] = \"PgInteger\";\n  getSQLType() {\n    return \"integer\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      return Number.parseInt(value);\n    }\n    return value;\n  }\n}\nfunction integer(name) {\n  return new PgIntegerBuilder(name ?? \"\");\n}\nexport {\n  PgInteger,\n  PgIntegerBuilder,\n  integer\n};\n//# sourceMappingURL=integer.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgIntervalBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgIntervalBuilder\";\n  constructor(name, intervalConfig) {\n    super(name, \"string\", \"PgInterval\");\n    this.config.intervalConfig = intervalConfig;\n  }\n  /** @internal */\n  build(table) {\n    return new PgInterval(table, this.config);\n  }\n}\nclass PgInterval extends PgColumn {\n  static [entityKind] = \"PgInterval\";\n  fields = this.config.intervalConfig.fields;\n  precision = this.config.intervalConfig.precision;\n  getSQLType() {\n    const fields = this.fields ? ` ${this.fields}` : \"\";\n    const precision = this.precision ? `(${this.precision})` : \"\";\n    return `interval${fields}${precision}`;\n  }\n}\nfunction interval(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgIntervalBuilder(name, config);\n}\nexport {\n  PgInterval,\n  PgIntervalBuilder,\n  interval\n};\n//# sourceMappingURL=interval.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgJsonBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgJsonBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgJson\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgJson(table, this.config);\n  }\n}\nclass PgJson extends PgColumn {\n  static [entityKind] = \"PgJson\";\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return \"json\";\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      try {\n        return JSON.parse(value);\n      } catch {\n        return value;\n      }\n    }\n    return value;\n  }\n}\nfunction json(name) {\n  return new PgJsonBuilder(name ?? \"\");\n}\nexport {\n  PgJson,\n  PgJsonBuilder,\n  json\n};\n//# sourceMappingURL=json.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgJsonbBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgJsonbBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgJsonb\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgJsonb(table, this.config);\n  }\n}\nclass PgJsonb extends PgColumn {\n  static [entityKind] = \"PgJsonb\";\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return \"jsonb\";\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      try {\n        return JSON.parse(value);\n      } catch {\n        return value;\n      }\n    }\n    return value;\n  }\n}\nfunction jsonb(name) {\n  return new PgJsonbBuilder(name ?? \"\");\n}\nexport {\n  PgJsonb,\n  PgJsonbBuilder,\n  jsonb\n};\n//# sourceMappingURL=jsonb.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgLineBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgLineBuilder\";\n  constructor(name) {\n    super(name, \"array\", \"PgLine\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgLineTuple(\n      table,\n      this.config\n    );\n  }\n}\nclass PgLineTuple extends PgColumn {\n  static [entityKind] = \"PgLine\";\n  getSQLType() {\n    return \"line\";\n  }\n  mapFromDriverValue(value) {\n    const [a, b, c] = value.slice(1, -1).split(\",\");\n    return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)];\n  }\n  mapToDriverValue(value) {\n    return `{${value[0]},${value[1]},${value[2]}}`;\n  }\n}\nclass PgLineABCBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgLineABCBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgLineABC\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgLineABC(\n      table,\n      this.config\n    );\n  }\n}\nclass PgLineABC extends PgColumn {\n  static [entityKind] = \"PgLineABC\";\n  getSQLType() {\n    return \"line\";\n  }\n  mapFromDriverValue(value) {\n    const [a, b, c] = value.slice(1, -1).split(\",\");\n    return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) };\n  }\n  mapToDriverValue(value) {\n    return `{${value.a},${value.b},${value.c}}`;\n  }\n}\nfunction line(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (!config?.mode || config.mode === \"tuple\") {\n    return new PgLineBuilder(name);\n  }\n  return new PgLineABCBuilder(name);\n}\nexport {\n  PgLineABC,\n  PgLineABCBuilder,\n  PgLineBuilder,\n  PgLineTuple,\n  line\n};\n//# sourceMappingURL=line.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgMacaddrBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgMacaddrBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgMacaddr\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgMacaddr(table, this.config);\n  }\n}\nclass PgMacaddr extends PgColumn {\n  static [entityKind] = \"PgMacaddr\";\n  getSQLType() {\n    return \"macaddr\";\n  }\n}\nfunction macaddr(name) {\n  return new PgMacaddrBuilder(name ?? \"\");\n}\nexport {\n  PgMacaddr,\n  PgMacaddrBuilder,\n  macaddr\n};\n//# sourceMappingURL=macaddr.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgMacaddr8Builder extends PgColumnBuilder {\n  static [entityKind] = \"PgMacaddr8Builder\";\n  constructor(name) {\n    super(name, \"string\", \"PgMacaddr8\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgMacaddr8(table, this.config);\n  }\n}\nclass PgMacaddr8 extends PgColumn {\n  static [entityKind] = \"PgMacaddr8\";\n  getSQLType() {\n    return \"macaddr8\";\n  }\n}\nfunction macaddr8(name) {\n  return new PgMacaddr8Builder(name ?? \"\");\n}\nexport {\n  PgMacaddr8,\n  PgMacaddr8Builder,\n  macaddr8\n};\n//# sourceMappingURL=macaddr8.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgNumericBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgNumericBuilder\";\n  constructor(name, precision, scale) {\n    super(name, \"string\", \"PgNumeric\");\n    this.config.precision = precision;\n    this.config.scale = scale;\n  }\n  /** @internal */\n  build(table) {\n    return new PgNumeric(table, this.config);\n  }\n}\nclass PgNumeric extends PgColumn {\n  static [entityKind] = \"PgNumeric\";\n  precision;\n  scale;\n  constructor(table, config) {\n    super(table, config);\n    this.precision = config.precision;\n    this.scale = config.scale;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    return String(value);\n  }\n  getSQLType() {\n    if (this.precision !== void 0 && this.scale !== void 0) {\n      return `numeric(${this.precision}, ${this.scale})`;\n    } else if (this.precision === void 0) {\n      return \"numeric\";\n    } else {\n      return `numeric(${this.precision})`;\n    }\n  }\n}\nclass PgNumericNumberBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgNumericNumberBuilder\";\n  constructor(name, precision, scale) {\n    super(name, \"number\", \"PgNumericNumber\");\n    this.config.precision = precision;\n    this.config.scale = scale;\n  }\n  /** @internal */\n  build(table) {\n    return new PgNumericNumber(\n      table,\n      this.config\n    );\n  }\n}\nclass PgNumericNumber extends PgColumn {\n  static [entityKind] = \"PgNumericNumber\";\n  precision;\n  scale;\n  constructor(table, config) {\n    super(table, config);\n    this.precision = config.precision;\n    this.scale = config.scale;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") return value;\n    return Number(value);\n  }\n  mapToDriverValue = String;\n  getSQLType() {\n    if (this.precision !== void 0 && this.scale !== void 0) {\n      return `numeric(${this.precision}, ${this.scale})`;\n    } else if (this.precision === void 0) {\n      return \"numeric\";\n    } else {\n      return `numeric(${this.precision})`;\n    }\n  }\n}\nclass PgNumericBigIntBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgNumericBigIntBuilder\";\n  constructor(name, precision, scale) {\n    super(name, \"bigint\", \"PgNumericBigInt\");\n    this.config.precision = precision;\n    this.config.scale = scale;\n  }\n  /** @internal */\n  build(table) {\n    return new PgNumericBigInt(\n      table,\n      this.config\n    );\n  }\n}\nclass PgNumericBigInt extends PgColumn {\n  static [entityKind] = \"PgNumericBigInt\";\n  precision;\n  scale;\n  constructor(table, config) {\n    super(table, config);\n    this.precision = config.precision;\n    this.scale = config.scale;\n  }\n  mapFromDriverValue = BigInt;\n  mapToDriverValue = String;\n  getSQLType() {\n    if (this.precision !== void 0 && this.scale !== void 0) {\n      return `numeric(${this.precision}, ${this.scale})`;\n    } else if (this.precision === void 0) {\n      return \"numeric\";\n    } else {\n      return `numeric(${this.precision})`;\n    }\n  }\n}\nfunction numeric(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  const mode = config?.mode;\n  return mode === \"number\" ? new PgNumericNumberBuilder(name, config?.precision, config?.scale) : mode === \"bigint\" ? new PgNumericBigIntBuilder(name, config?.precision, config?.scale) : new PgNumericBuilder(name, config?.precision, config?.scale);\n}\nconst decimal = numeric;\nexport {\n  PgNumeric,\n  PgNumericBigInt,\n  PgNumericBigIntBuilder,\n  PgNumericBuilder,\n  PgNumericNumber,\n  PgNumericNumberBuilder,\n  decimal,\n  numeric\n};\n//# sourceMappingURL=numeric.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgPointTupleBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgPointTupleBuilder\";\n  constructor(name) {\n    super(name, \"array\", \"PgPointTuple\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgPointTuple(\n      table,\n      this.config\n    );\n  }\n}\nclass PgPointTuple extends PgColumn {\n  static [entityKind] = \"PgPointTuple\";\n  getSQLType() {\n    return \"point\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      const [x, y] = value.slice(1, -1).split(\",\");\n      return [Number.parseFloat(x), Number.parseFloat(y)];\n    }\n    return [value.x, value.y];\n  }\n  mapToDriverValue(value) {\n    return `(${value[0]},${value[1]})`;\n  }\n}\nclass PgPointObjectBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgPointObjectBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgPointObject\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgPointObject(\n      table,\n      this.config\n    );\n  }\n}\nclass PgPointObject extends PgColumn {\n  static [entityKind] = \"PgPointObject\";\n  getSQLType() {\n    return \"point\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      const [x, y] = value.slice(1, -1).split(\",\");\n      return { x: Number.parseFloat(x), y: Number.parseFloat(y) };\n    }\n    return value;\n  }\n  mapToDriverValue(value) {\n    return `(${value.x},${value.y})`;\n  }\n}\nfunction point(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (!config?.mode || config.mode === \"tuple\") {\n    return new PgPointTupleBuilder(name);\n  }\n  return new PgPointObjectBuilder(name);\n}\nexport {\n  PgPointObject,\n  PgPointObjectBuilder,\n  PgPointTuple,\n  PgPointTupleBuilder,\n  point\n};\n//# sourceMappingURL=point.js.map","function hexToBytes(hex) {\n  const bytes = [];\n  for (let c = 0; c < hex.length; c += 2) {\n    bytes.push(Number.parseInt(hex.slice(c, c + 2), 16));\n  }\n  return new Uint8Array(bytes);\n}\nfunction bytesToFloat64(bytes, offset) {\n  const buffer = new ArrayBuffer(8);\n  const view = new DataView(buffer);\n  for (let i = 0; i < 8; i++) {\n    view.setUint8(i, bytes[offset + i]);\n  }\n  return view.getFloat64(0, true);\n}\nfunction parseEWKB(hex) {\n  const bytes = hexToBytes(hex);\n  let offset = 0;\n  const byteOrder = bytes[offset];\n  offset += 1;\n  const view = new DataView(bytes.buffer);\n  const geomType = view.getUint32(offset, byteOrder === 1);\n  offset += 4;\n  let _srid;\n  if (geomType & 536870912) {\n    _srid = view.getUint32(offset, byteOrder === 1);\n    offset += 4;\n  }\n  if ((geomType & 65535) === 1) {\n    const x = bytesToFloat64(bytes, offset);\n    offset += 8;\n    const y = bytesToFloat64(bytes, offset);\n    offset += 8;\n    return [x, y];\n  }\n  throw new Error(\"Unsupported geometry type\");\n}\nexport {\n  parseEWKB\n};\n//# sourceMappingURL=utils.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nimport { parseEWKB } from \"./utils.js\";\nclass PgGeometryBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgGeometryBuilder\";\n  constructor(name) {\n    super(name, \"array\", \"PgGeometry\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgGeometry(\n      table,\n      this.config\n    );\n  }\n}\nclass PgGeometry extends PgColumn {\n  static [entityKind] = \"PgGeometry\";\n  getSQLType() {\n    return \"geometry(point)\";\n  }\n  mapFromDriverValue(value) {\n    return parseEWKB(value);\n  }\n  mapToDriverValue(value) {\n    return `point(${value[0]} ${value[1]})`;\n  }\n}\nclass PgGeometryObjectBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgGeometryObjectBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgGeometryObject\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgGeometryObject(\n      table,\n      this.config\n    );\n  }\n}\nclass PgGeometryObject extends PgColumn {\n  static [entityKind] = \"PgGeometryObject\";\n  getSQLType() {\n    return \"geometry(point)\";\n  }\n  mapFromDriverValue(value) {\n    const parsed = parseEWKB(value);\n    return { x: parsed[0], y: parsed[1] };\n  }\n  mapToDriverValue(value) {\n    return `point(${value.x} ${value.y})`;\n  }\n}\nfunction geometry(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (!config?.mode || config.mode === \"tuple\") {\n    return new PgGeometryBuilder(name);\n  }\n  return new PgGeometryObjectBuilder(name);\n}\nexport {\n  PgGeometry,\n  PgGeometryBuilder,\n  PgGeometryObject,\n  PgGeometryObjectBuilder,\n  geometry\n};\n//# sourceMappingURL=geometry.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgRealBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgRealBuilder\";\n  constructor(name, length) {\n    super(name, \"number\", \"PgReal\");\n    this.config.length = length;\n  }\n  /** @internal */\n  build(table) {\n    return new PgReal(table, this.config);\n  }\n}\nclass PgReal extends PgColumn {\n  static [entityKind] = \"PgReal\";\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return \"real\";\n  }\n  mapFromDriverValue = (value) => {\n    if (typeof value === \"string\") {\n      return Number.parseFloat(value);\n    }\n    return value;\n  };\n}\nfunction real(name) {\n  return new PgRealBuilder(name ?? \"\");\n}\nexport {\n  PgReal,\n  PgRealBuilder,\n  real\n};\n//# sourceMappingURL=real.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgSerialBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgSerialBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgSerial\");\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgSerial(table, this.config);\n  }\n}\nclass PgSerial extends PgColumn {\n  static [entityKind] = \"PgSerial\";\n  getSQLType() {\n    return \"serial\";\n  }\n}\nfunction serial(name) {\n  return new PgSerialBuilder(name ?? \"\");\n}\nexport {\n  PgSerial,\n  PgSerialBuilder,\n  serial\n};\n//# sourceMappingURL=serial.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgIntColumnBaseBuilder } from \"./int.common.js\";\nclass PgSmallIntBuilder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgSmallIntBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgSmallInt\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgSmallInt(table, this.config);\n  }\n}\nclass PgSmallInt extends PgColumn {\n  static [entityKind] = \"PgSmallInt\";\n  getSQLType() {\n    return \"smallint\";\n  }\n  mapFromDriverValue = (value) => {\n    if (typeof value === \"string\") {\n      return Number(value);\n    }\n    return value;\n  };\n}\nfunction smallint(name) {\n  return new PgSmallIntBuilder(name ?? \"\");\n}\nexport {\n  PgSmallInt,\n  PgSmallIntBuilder,\n  smallint\n};\n//# sourceMappingURL=smallint.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgSmallSerialBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgSmallSerialBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgSmallSerial\");\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgSmallSerial(\n      table,\n      this.config\n    );\n  }\n}\nclass PgSmallSerial extends PgColumn {\n  static [entityKind] = \"PgSmallSerial\";\n  getSQLType() {\n    return \"smallserial\";\n  }\n}\nfunction smallserial(name) {\n  return new PgSmallSerialBuilder(name ?? \"\");\n}\nexport {\n  PgSmallSerial,\n  PgSmallSerialBuilder,\n  smallserial\n};\n//# sourceMappingURL=smallserial.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgTextBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgTextBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgText\");\n    this.config.enumValues = config.enum;\n  }\n  /** @internal */\n  build(table) {\n    return new PgText(table, this.config);\n  }\n}\nclass PgText extends PgColumn {\n  static [entityKind] = \"PgText\";\n  enumValues = this.config.enumValues;\n  getSQLType() {\n    return \"text\";\n  }\n}\nfunction text(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgTextBuilder(name, config);\n}\nexport {\n  PgText,\n  PgTextBuilder,\n  text\n};\n//# sourceMappingURL=text.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgDateColumnBaseBuilder } from \"./date.common.js\";\nclass PgTimeBuilder extends PgDateColumnBaseBuilder {\n  constructor(name, withTimezone, precision) {\n    super(name, \"string\", \"PgTime\");\n    this.withTimezone = withTimezone;\n    this.precision = precision;\n    this.config.withTimezone = withTimezone;\n    this.config.precision = precision;\n  }\n  static [entityKind] = \"PgTimeBuilder\";\n  /** @internal */\n  build(table) {\n    return new PgTime(table, this.config);\n  }\n}\nclass PgTime extends PgColumn {\n  static [entityKind] = \"PgTime\";\n  withTimezone;\n  precision;\n  constructor(table, config) {\n    super(table, config);\n    this.withTimezone = config.withTimezone;\n    this.precision = config.precision;\n  }\n  getSQLType() {\n    const precision = this.precision === void 0 ? \"\" : `(${this.precision})`;\n    return `time${precision}${this.withTimezone ? \" with time zone\" : \"\"}`;\n  }\n}\nfunction time(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgTimeBuilder(name, config.withTimezone ?? false, config.precision);\n}\nexport {\n  PgTime,\n  PgTimeBuilder,\n  time\n};\n//# sourceMappingURL=time.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgDateColumnBaseBuilder } from \"./date.common.js\";\nclass PgTimestampBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgTimestampBuilder\";\n  constructor(name, withTimezone, precision) {\n    super(name, \"date\", \"PgTimestamp\");\n    this.config.withTimezone = withTimezone;\n    this.config.precision = precision;\n  }\n  /** @internal */\n  build(table) {\n    return new PgTimestamp(table, this.config);\n  }\n}\nclass PgTimestamp extends PgColumn {\n  static [entityKind] = \"PgTimestamp\";\n  withTimezone;\n  precision;\n  constructor(table, config) {\n    super(table, config);\n    this.withTimezone = config.withTimezone;\n    this.precision = config.precision;\n  }\n  getSQLType() {\n    const precision = this.precision === void 0 ? \"\" : ` (${this.precision})`;\n    return `timestamp${precision}${this.withTimezone ? \" with time zone\" : \"\"}`;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return new Date(this.withTimezone ? value : value + \"+0000\");\n    return value;\n  }\n  mapToDriverValue = (value) => {\n    return value.toISOString();\n  };\n}\nclass PgTimestampStringBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgTimestampStringBuilder\";\n  constructor(name, withTimezone, precision) {\n    super(name, \"string\", \"PgTimestampString\");\n    this.config.withTimezone = withTimezone;\n    this.config.precision = precision;\n  }\n  /** @internal */\n  build(table) {\n    return new PgTimestampString(\n      table,\n      this.config\n    );\n  }\n}\nclass PgTimestampString extends PgColumn {\n  static [entityKind] = \"PgTimestampString\";\n  withTimezone;\n  precision;\n  constructor(table, config) {\n    super(table, config);\n    this.withTimezone = config.withTimezone;\n    this.precision = config.precision;\n  }\n  getSQLType() {\n    const precision = this.precision === void 0 ? \"\" : `(${this.precision})`;\n    return `timestamp${precision}${this.withTimezone ? \" with time zone\" : \"\"}`;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    const shortened = value.toISOString().slice(0, -1).replace(\"T\", \" \");\n    if (this.withTimezone) {\n      const offset = value.getTimezoneOffset();\n      const sign = offset <= 0 ? \"+\" : \"-\";\n      return `${shortened}${sign}${Math.floor(Math.abs(offset) / 60).toString().padStart(2, \"0\")}`;\n    }\n    return shortened;\n  }\n}\nfunction timestamp(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"string\") {\n    return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision);\n  }\n  return new PgTimestampBuilder(name, config?.withTimezone ?? false, config?.precision);\n}\nexport {\n  PgTimestamp,\n  PgTimestampBuilder,\n  PgTimestampString,\n  PgTimestampStringBuilder,\n  timestamp\n};\n//# sourceMappingURL=timestamp.js.map","import { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgUUIDBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgUUIDBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgUUID\");\n  }\n  /**\n   * Adds `default gen_random_uuid()` to the column definition.\n   */\n  defaultRandom() {\n    return this.default(sql`gen_random_uuid()`);\n  }\n  /** @internal */\n  build(table) {\n    return new PgUUID(table, this.config);\n  }\n}\nclass PgUUID extends PgColumn {\n  static [entityKind] = \"PgUUID\";\n  getSQLType() {\n    return \"uuid\";\n  }\n}\nfunction uuid(name) {\n  return new PgUUIDBuilder(name ?? \"\");\n}\nexport {\n  PgUUID,\n  PgUUIDBuilder,\n  uuid\n};\n//# sourceMappingURL=uuid.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgVarcharBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgVarcharBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgVarchar\");\n    this.config.length = config.length;\n    this.config.enumValues = config.enum;\n  }\n  /** @internal */\n  build(table) {\n    return new PgVarchar(\n      table,\n      this.config\n    );\n  }\n}\nclass PgVarchar extends PgColumn {\n  static [entityKind] = \"PgVarchar\";\n  length = this.config.length;\n  enumValues = this.config.enumValues;\n  getSQLType() {\n    return this.length === void 0 ? `varchar` : `varchar(${this.length})`;\n  }\n}\nfunction varchar(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgVarcharBuilder(name, config);\n}\nexport {\n  PgVarchar,\n  PgVarcharBuilder,\n  varchar\n};\n//# sourceMappingURL=varchar.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgBinaryVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgBinaryVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgBinaryVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgBinaryVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBinaryVector extends PgColumn {\n  static [entityKind] = \"PgBinaryVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `bit(${this.dimensions})`;\n  }\n}\nfunction bit(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgBinaryVectorBuilder(name, config);\n}\nexport {\n  PgBinaryVector,\n  PgBinaryVectorBuilder,\n  bit\n};\n//# sourceMappingURL=bit.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgHalfVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgHalfVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"array\", \"PgHalfVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgHalfVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgHalfVector extends PgColumn {\n  static [entityKind] = \"PgHalfVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `halfvec(${this.dimensions})`;\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    return value.slice(1, -1).split(\",\").map((v) => Number.parseFloat(v));\n  }\n}\nfunction halfvec(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgHalfVectorBuilder(name, config);\n}\nexport {\n  PgHalfVector,\n  PgHalfVectorBuilder,\n  halfvec\n};\n//# sourceMappingURL=halfvec.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgSparseVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgSparseVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgSparseVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgSparseVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgSparseVector extends PgColumn {\n  static [entityKind] = \"PgSparseVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `sparsevec(${this.dimensions})`;\n  }\n}\nfunction sparsevec(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgSparseVectorBuilder(name, config);\n}\nexport {\n  PgSparseVector,\n  PgSparseVectorBuilder,\n  sparsevec\n};\n//# sourceMappingURL=sparsevec.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"array\", \"PgVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgVector extends PgColumn {\n  static [entityKind] = \"PgVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `vector(${this.dimensions})`;\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    return value.slice(1, -1).split(\",\").map((v) => Number.parseFloat(v));\n  }\n}\nfunction vector(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgVectorBuilder(name, config);\n}\nexport {\n  PgVector,\n  PgVectorBuilder,\n  vector\n};\n//# sourceMappingURL=vector.js.map","import { bigint } from \"./bigint.js\";\nimport { bigserial } from \"./bigserial.js\";\nimport { boolean } from \"./boolean.js\";\nimport { char } from \"./char.js\";\nimport { cidr } from \"./cidr.js\";\nimport { customType } from \"./custom.js\";\nimport { date } from \"./date.js\";\nimport { doublePrecision } from \"./double-precision.js\";\nimport { inet } from \"./inet.js\";\nimport { integer } from \"./integer.js\";\nimport { interval } from \"./interval.js\";\nimport { json } from \"./json.js\";\nimport { jsonb } from \"./jsonb.js\";\nimport { line } from \"./line.js\";\nimport { macaddr } from \"./macaddr.js\";\nimport { macaddr8 } from \"./macaddr8.js\";\nimport { numeric } from \"./numeric.js\";\nimport { point } from \"./point.js\";\nimport { geometry } from \"./postgis_extension/geometry.js\";\nimport { real } from \"./real.js\";\nimport { serial } from \"./serial.js\";\nimport { smallint } from \"./smallint.js\";\nimport { smallserial } from \"./smallserial.js\";\nimport { text } from \"./text.js\";\nimport { time } from \"./time.js\";\nimport { timestamp } from \"./timestamp.js\";\nimport { uuid } from \"./uuid.js\";\nimport { varchar } from \"./varchar.js\";\nimport { bit } from \"./vector_extension/bit.js\";\nimport { halfvec } from \"./vector_extension/halfvec.js\";\nimport { sparsevec } from \"./vector_extension/sparsevec.js\";\nimport { vector } from \"./vector_extension/vector.js\";\nfunction getPgColumnBuilders() {\n  return {\n    bigint,\n    bigserial,\n    boolean,\n    char,\n    cidr,\n    customType,\n    date,\n    doublePrecision,\n    inet,\n    integer,\n    interval,\n    json,\n    jsonb,\n    line,\n    macaddr,\n    macaddr8,\n    numeric,\n    point,\n    geometry,\n    real,\n    serial,\n    smallint,\n    smallserial,\n    text,\n    time,\n    timestamp,\n    uuid,\n    varchar,\n    bit,\n    halfvec,\n    sparsevec,\n    vector\n  };\n}\nexport {\n  getPgColumnBuilders\n};\n//# sourceMappingURL=all.js.map","import { entityKind } from \"../entity.js\";\nimport { Table } from \"../table.js\";\nimport { getPgColumnBuilders } from \"./columns/all.js\";\nconst InlineForeignKeys = Symbol.for(\"drizzle:PgInlineForeignKeys\");\nconst EnableRLS = Symbol.for(\"drizzle:EnableRLS\");\nclass PgTable extends Table {\n  static [entityKind] = \"PgTable\";\n  /** @internal */\n  static Symbol = Object.assign({}, Table.Symbol, {\n    InlineForeignKeys,\n    EnableRLS\n  });\n  /**@internal */\n  [InlineForeignKeys] = [];\n  /** @internal */\n  [EnableRLS] = false;\n  /** @internal */\n  [Table.Symbol.ExtraConfigBuilder] = void 0;\n  /** @internal */\n  [Table.Symbol.ExtraConfigColumns] = {};\n}\nfunction pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) {\n  const rawTable = new PgTable(name, schema, baseName);\n  const parsedColumns = typeof columns === \"function\" ? columns(getPgColumnBuilders()) : columns;\n  const builtColumns = Object.fromEntries(\n    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {\n      const colBuilder = colBuilderBase;\n      colBuilder.setName(name2);\n      const column = colBuilder.build(rawTable);\n      rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n      return [name2, column];\n    })\n  );\n  const builtColumnsForExtraConfig = Object.fromEntries(\n    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {\n      const colBuilder = colBuilderBase;\n      colBuilder.setName(name2);\n      const column = colBuilder.buildExtraConfigColumn(rawTable);\n      return [name2, column];\n    })\n  );\n  const table = Object.assign(rawTable, builtColumns);\n  table[Table.Symbol.Columns] = builtColumns;\n  table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;\n  if (extraConfig) {\n    table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig;\n  }\n  return Object.assign(table, {\n    enableRLS: () => {\n      table[PgTable.Symbol.EnableRLS] = true;\n      return table;\n    }\n  });\n}\nconst pgTable = (name, columns, extraConfig) => {\n  return pgTableWithSchema(name, columns, extraConfig, void 0);\n};\nfunction pgTableCreator(customizeTableName) {\n  return (name, columns, extraConfig) => {\n    return pgTableWithSchema(customizeTableName(name), columns, extraConfig, void 0, name);\n  };\n}\nexport {\n  EnableRLS,\n  InlineForeignKeys,\n  PgTable,\n  pgTable,\n  pgTableCreator,\n  pgTableWithSchema\n};\n//# sourceMappingURL=table.js.map","import { SQL } from \"../sql/sql.js\";\nimport { entityKind, is } from \"../entity.js\";\nimport { IndexedColumn } from \"./columns/index.js\";\nclass IndexBuilderOn {\n  constructor(unique, name) {\n    this.unique = unique;\n    this.name = name;\n  }\n  static [entityKind] = \"PgIndexBuilderOn\";\n  on(...columns) {\n    return new IndexBuilder(\n      columns.map((it) => {\n        if (is(it, SQL)) {\n          return it;\n        }\n        it = it;\n        const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);\n        it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));\n        return clonedIndexedColumn;\n      }),\n      this.unique,\n      false,\n      this.name\n    );\n  }\n  onOnly(...columns) {\n    return new IndexBuilder(\n      columns.map((it) => {\n        if (is(it, SQL)) {\n          return it;\n        }\n        it = it;\n        const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);\n        it.indexConfig = it.defaultConfig;\n        return clonedIndexedColumn;\n      }),\n      this.unique,\n      true,\n      this.name\n    );\n  }\n  /**\n   * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.\n   *\n   * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.\n   *\n   * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**\n   *\n   * @param method The name of the index method to be used\n   * @param columns\n   * @returns\n   */\n  using(method, ...columns) {\n    return new IndexBuilder(\n      columns.map((it) => {\n        if (is(it, SQL)) {\n          return it;\n        }\n        it = it;\n        const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);\n        it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));\n        return clonedIndexedColumn;\n      }),\n      this.unique,\n      true,\n      this.name,\n      method\n    );\n  }\n}\nclass IndexBuilder {\n  static [entityKind] = \"PgIndexBuilder\";\n  /** @internal */\n  config;\n  constructor(columns, unique, only, name, method = \"btree\") {\n    this.config = {\n      name,\n      columns,\n      unique,\n      only,\n      method\n    };\n  }\n  concurrently() {\n    this.config.concurrently = true;\n    return this;\n  }\n  with(obj) {\n    this.config.with = obj;\n    return this;\n  }\n  where(condition) {\n    this.config.where = condition;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new Index(this.config, table);\n  }\n}\nclass Index {\n  static [entityKind] = \"PgIndex\";\n  config;\n  constructor(config, table) {\n    this.config = { ...config, table };\n  }\n}\nfunction index(name) {\n  return new IndexBuilderOn(false, name);\n}\nfunction uniqueIndex(name) {\n  return new IndexBuilderOn(true, name);\n}\nexport {\n  Index,\n  IndexBuilder,\n  IndexBuilderOn,\n  index,\n  uniqueIndex\n};\n//# sourceMappingURL=indexes.js.map","import { entityKind } from \"../entity.js\";\nimport { PgTable } from \"./table.js\";\nfunction primaryKey(...config) {\n  if (config[0].columns) {\n    return new PrimaryKeyBuilder(config[0].columns, config[0].name);\n  }\n  return new PrimaryKeyBuilder(config);\n}\nclass PrimaryKeyBuilder {\n  static [entityKind] = \"PgPrimaryKeyBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  name;\n  constructor(columns, name) {\n    this.columns = columns;\n    this.name = name;\n  }\n  /** @internal */\n  build(table) {\n    return new PrimaryKey(table, this.columns, this.name);\n  }\n}\nclass PrimaryKey {\n  constructor(table, columns, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name;\n  }\n  static [entityKind] = \"PgPrimaryKey\";\n  columns;\n  name;\n  getName() {\n    return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join(\"_\")}_pk`;\n  }\n}\nexport {\n  PrimaryKey,\n  PrimaryKeyBuilder,\n  primaryKey\n};\n//# sourceMappingURL=primary-keys.js.map","import { Column } from \"../../column.js\";\nimport { is } from \"../../entity.js\";\nimport { Table } from \"../../table.js\";\nimport {\n  isDriverValueEncoder,\n  isSQLWrapper,\n  Param,\n  Placeholder,\n  SQL,\n  sql,\n  StringChunk,\n  View\n} from \"../sql.js\";\nfunction bindIfParam(value, column) {\n  if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {\n    return new Param(value, column);\n  }\n  return value;\n}\nconst eq = (left, right) => {\n  return sql`${left} = ${bindIfParam(right, left)}`;\n};\nconst ne = (left, right) => {\n  return sql`${left} <> ${bindIfParam(right, left)}`;\n};\nfunction and(...unfilteredConditions) {\n  const conditions = unfilteredConditions.filter(\n    (c) => c !== void 0\n  );\n  if (conditions.length === 0) {\n    return void 0;\n  }\n  if (conditions.length === 1) {\n    return new SQL(conditions);\n  }\n  return new SQL([\n    new StringChunk(\"(\"),\n    sql.join(conditions, new StringChunk(\" and \")),\n    new StringChunk(\")\")\n  ]);\n}\nfunction or(...unfilteredConditions) {\n  const conditions = unfilteredConditions.filter(\n    (c) => c !== void 0\n  );\n  if (conditions.length === 0) {\n    return void 0;\n  }\n  if (conditions.length === 1) {\n    return new SQL(conditions);\n  }\n  return new SQL([\n    new StringChunk(\"(\"),\n    sql.join(conditions, new StringChunk(\" or \")),\n    new StringChunk(\")\")\n  ]);\n}\nfunction not(condition) {\n  return sql`not ${condition}`;\n}\nconst gt = (left, right) => {\n  return sql`${left} > ${bindIfParam(right, left)}`;\n};\nconst gte = (left, right) => {\n  return sql`${left} >= ${bindIfParam(right, left)}`;\n};\nconst lt = (left, right) => {\n  return sql`${left} < ${bindIfParam(right, left)}`;\n};\nconst lte = (left, right) => {\n  return sql`${left} <= ${bindIfParam(right, left)}`;\n};\nfunction inArray(column, values) {\n  if (Array.isArray(values)) {\n    if (values.length === 0) {\n      return sql`false`;\n    }\n    return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;\n  }\n  return sql`${column} in ${bindIfParam(values, column)}`;\n}\nfunction notInArray(column, values) {\n  if (Array.isArray(values)) {\n    if (values.length === 0) {\n      return sql`true`;\n    }\n    return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;\n  }\n  return sql`${column} not in ${bindIfParam(values, column)}`;\n}\nfunction isNull(value) {\n  return sql`${value} is null`;\n}\nfunction isNotNull(value) {\n  return sql`${value} is not null`;\n}\nfunction exists(subquery) {\n  return sql`exists ${subquery}`;\n}\nfunction notExists(subquery) {\n  return sql`not exists ${subquery}`;\n}\nfunction between(column, min, max) {\n  return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(\n    max,\n    column\n  )}`;\n}\nfunction notBetween(column, min, max) {\n  return sql`${column} not between ${bindIfParam(\n    min,\n    column\n  )} and ${bindIfParam(max, column)}`;\n}\nfunction like(column, value) {\n  return sql`${column} like ${value}`;\n}\nfunction notLike(column, value) {\n  return sql`${column} not like ${value}`;\n}\nfunction ilike(column, value) {\n  return sql`${column} ilike ${value}`;\n}\nfunction notIlike(column, value) {\n  return sql`${column} not ilike ${value}`;\n}\nfunction arrayContains(column, values) {\n  if (Array.isArray(values)) {\n    if (values.length === 0) {\n      throw new Error(\"arrayContains requires at least one value\");\n    }\n    const array = sql`${bindIfParam(values, column)}`;\n    return sql`${column} @> ${array}`;\n  }\n  return sql`${column} @> ${bindIfParam(values, column)}`;\n}\nfunction arrayContained(column, values) {\n  if (Array.isArray(values)) {\n    if (values.length === 0) {\n      throw new Error(\"arrayContained requires at least one value\");\n    }\n    const array = sql`${bindIfParam(values, column)}`;\n    return sql`${column} <@ ${array}`;\n  }\n  return sql`${column} <@ ${bindIfParam(values, column)}`;\n}\nfunction arrayOverlaps(column, values) {\n  if (Array.isArray(values)) {\n    if (values.length === 0) {\n      throw new Error(\"arrayOverlaps requires at least one value\");\n    }\n    const array = sql`${bindIfParam(values, column)}`;\n    return sql`${column} && ${array}`;\n  }\n  return sql`${column} && ${bindIfParam(values, column)}`;\n}\nexport {\n  and,\n  arrayContained,\n  arrayContains,\n  arrayOverlaps,\n  between,\n  bindIfParam,\n  eq,\n  exists,\n  gt,\n  gte,\n  ilike,\n  inArray,\n  isNotNull,\n  isNull,\n  like,\n  lt,\n  lte,\n  ne,\n  not,\n  notBetween,\n  notExists,\n  notIlike,\n  notInArray,\n  notLike,\n  or\n};\n//# sourceMappingURL=conditions.js.map","import { sql } from \"../sql.js\";\nfunction asc(column) {\n  return sql`${column} asc`;\n}\nfunction desc(column) {\n  return sql`${column} desc`;\n}\nexport {\n  asc,\n  desc\n};\n//# sourceMappingURL=select.js.map","import { Column } from \"../../column.js\";\nimport { is } from \"../../entity.js\";\nimport { sql } from \"../sql.js\";\nfunction count(expression) {\n  return sql`count(${expression || sql.raw(\"*\")})`.mapWith(Number);\n}\nfunction countDistinct(expression) {\n  return sql`count(distinct ${expression})`.mapWith(Number);\n}\nfunction avg(expression) {\n  return sql`avg(${expression})`.mapWith(String);\n}\nfunction avgDistinct(expression) {\n  return sql`avg(distinct ${expression})`.mapWith(String);\n}\nfunction sum(expression) {\n  return sql`sum(${expression})`.mapWith(String);\n}\nfunction sumDistinct(expression) {\n  return sql`sum(distinct ${expression})`.mapWith(String);\n}\nfunction max(expression) {\n  return sql`max(${expression})`.mapWith(is(expression, Column) ? expression : String);\n}\nfunction min(expression) {\n  return sql`min(${expression})`.mapWith(is(expression, Column) ? expression : String);\n}\nexport {\n  avg,\n  avgDistinct,\n  count,\n  countDistinct,\n  max,\n  min,\n  sum,\n  sumDistinct\n};\n//# sourceMappingURL=aggregate.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nclass ForeignKeyBuilder {\n  static [entityKind] = \"SQLiteForeignKeyBuilder\";\n  /** @internal */\n  reference;\n  /** @internal */\n  _onUpdate;\n  /** @internal */\n  _onDelete;\n  constructor(config, actions) {\n    this.reference = () => {\n      const { name, columns, foreignColumns } = config();\n      return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };\n    };\n    if (actions) {\n      this._onUpdate = actions.onUpdate;\n      this._onDelete = actions.onDelete;\n    }\n  }\n  onUpdate(action) {\n    this._onUpdate = action;\n    return this;\n  }\n  onDelete(action) {\n    this._onDelete = action;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new ForeignKey(table, this);\n  }\n}\nclass ForeignKey {\n  constructor(table, builder) {\n    this.table = table;\n    this.reference = builder.reference;\n    this.onUpdate = builder._onUpdate;\n    this.onDelete = builder._onDelete;\n  }\n  static [entityKind] = \"SQLiteForeignKey\";\n  reference;\n  onUpdate;\n  onDelete;\n  getName() {\n    const { name, columns, foreignColumns } = this.reference();\n    const columnNames = columns.map((column) => column.name);\n    const foreignColumnNames = foreignColumns.map((column) => column.name);\n    const chunks = [\n      this.table[TableName],\n      ...columnNames,\n      foreignColumns[0].table[TableName],\n      ...foreignColumnNames\n    ];\n    return name ?? `${chunks.join(\"_\")}_fk`;\n  }\n}\nfunction foreignKey(config) {\n  function mappedConfig() {\n    if (typeof config === \"function\") {\n      const { name, columns, foreignColumns } = config();\n      return {\n        name,\n        columns,\n        foreignColumns\n      };\n    }\n    return config;\n  }\n  return new ForeignKeyBuilder(mappedConfig);\n}\nexport {\n  ForeignKey,\n  ForeignKeyBuilder,\n  foreignKey\n};\n//# sourceMappingURL=foreign-keys.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nfunction uniqueKeyName(table, columns) {\n  return `${table[TableName]}_${columns.join(\"_\")}_unique`;\n}\nfunction unique(name) {\n  return new UniqueOnConstraintBuilder(name);\n}\nclass UniqueConstraintBuilder {\n  constructor(columns, name) {\n    this.name = name;\n    this.columns = columns;\n  }\n  static [entityKind] = \"SQLiteUniqueConstraintBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  build(table) {\n    return new UniqueConstraint(table, this.columns, this.name);\n  }\n}\nclass UniqueOnConstraintBuilder {\n  static [entityKind] = \"SQLiteUniqueOnConstraintBuilder\";\n  /** @internal */\n  name;\n  constructor(name) {\n    this.name = name;\n  }\n  on(...columns) {\n    return new UniqueConstraintBuilder(columns, this.name);\n  }\n}\nclass UniqueConstraint {\n  constructor(table, columns, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n  }\n  static [entityKind] = \"SQLiteUniqueConstraint\";\n  columns;\n  name;\n  getName() {\n    return this.name;\n  }\n}\nexport {\n  UniqueConstraint,\n  UniqueConstraintBuilder,\n  UniqueOnConstraintBuilder,\n  unique,\n  uniqueKeyName\n};\n//# sourceMappingURL=unique-constraint.js.map","import { ColumnBuilder } from \"../../column-builder.js\";\nimport { Column } from \"../../column.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { ForeignKeyBuilder } from \"../foreign-keys.js\";\nimport { uniqueKeyName } from \"../unique-constraint.js\";\nclass SQLiteColumnBuilder extends ColumnBuilder {\n  static [entityKind] = \"SQLiteColumnBuilder\";\n  foreignKeyConfigs = [];\n  references(ref, actions = {}) {\n    this.foreignKeyConfigs.push({ ref, actions });\n    return this;\n  }\n  unique(name) {\n    this.config.isUnique = true;\n    this.config.uniqueName = name;\n    return this;\n  }\n  generatedAlwaysAs(as, config) {\n    this.config.generated = {\n      as,\n      type: \"always\",\n      mode: config?.mode ?? \"virtual\"\n    };\n    return this;\n  }\n  /** @internal */\n  buildForeignKeys(column, table) {\n    return this.foreignKeyConfigs.map(({ ref, actions }) => {\n      return ((ref2, actions2) => {\n        const builder = new ForeignKeyBuilder(() => {\n          const foreignColumn = ref2();\n          return { columns: [column], foreignColumns: [foreignColumn] };\n        });\n        if (actions2.onUpdate) {\n          builder.onUpdate(actions2.onUpdate);\n        }\n        if (actions2.onDelete) {\n          builder.onDelete(actions2.onDelete);\n        }\n        return builder.build(table);\n      })(ref, actions);\n    });\n  }\n}\nclass SQLiteColumn extends Column {\n  constructor(table, config) {\n    if (!config.uniqueName) {\n      config.uniqueName = uniqueKeyName(table, [config.name]);\n    }\n    super(table, config);\n    this.table = table;\n  }\n  static [entityKind] = \"SQLiteColumn\";\n}\nexport {\n  SQLiteColumn,\n  SQLiteColumnBuilder\n};\n//# sourceMappingURL=common.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig, textDecoder } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteBigIntBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBigIntBuilder\";\n  constructor(name) {\n    super(name, \"bigint\", \"SQLiteBigInt\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteBigInt(table, this.config);\n  }\n}\nclass SQLiteBigInt extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBigInt\";\n  getSQLType() {\n    return \"blob\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof Buffer !== \"undefined\" && Buffer.from) {\n      const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);\n      return BigInt(buf.toString(\"utf8\"));\n    }\n    return BigInt(textDecoder.decode(value));\n  }\n  mapToDriverValue(value) {\n    return Buffer.from(value.toString());\n  }\n}\nclass SQLiteBlobJsonBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBlobJsonBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"SQLiteBlobJson\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteBlobJson(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteBlobJson extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBlobJson\";\n  getSQLType() {\n    return \"blob\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof Buffer !== \"undefined\" && Buffer.from) {\n      const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);\n      return JSON.parse(buf.toString(\"utf8\"));\n    }\n    return JSON.parse(textDecoder.decode(value));\n  }\n  mapToDriverValue(value) {\n    return Buffer.from(JSON.stringify(value));\n  }\n}\nclass SQLiteBlobBufferBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBlobBufferBuilder\";\n  constructor(name) {\n    super(name, \"buffer\", \"SQLiteBlobBuffer\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteBlobBuffer(table, this.config);\n  }\n}\nclass SQLiteBlobBuffer extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBlobBuffer\";\n  mapFromDriverValue(value) {\n    if (Buffer.isBuffer(value)) {\n      return value;\n    }\n    return Buffer.from(value);\n  }\n  getSQLType() {\n    return \"blob\";\n  }\n}\nfunction blob(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"json\") {\n    return new SQLiteBlobJsonBuilder(name);\n  }\n  if (config?.mode === \"bigint\") {\n    return new SQLiteBigIntBuilder(name);\n  }\n  return new SQLiteBlobBufferBuilder(name);\n}\nexport {\n  SQLiteBigInt,\n  SQLiteBigIntBuilder,\n  SQLiteBlobBuffer,\n  SQLiteBlobBufferBuilder,\n  SQLiteBlobJson,\n  SQLiteBlobJsonBuilder,\n  blob\n};\n//# sourceMappingURL=blob.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteCustomColumnBuilder\";\n  constructor(name, fieldConfig, customTypeParams) {\n    super(name, \"custom\", \"SQLiteCustomColumn\");\n    this.config.fieldConfig = fieldConfig;\n    this.config.customTypeParams = customTypeParams;\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteCustomColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteCustomColumn extends SQLiteColumn {\n  static [entityKind] = \"SQLiteCustomColumn\";\n  sqlName;\n  mapTo;\n  mapFrom;\n  constructor(table, config) {\n    super(table, config);\n    this.sqlName = config.customTypeParams.dataType(config.fieldConfig);\n    this.mapTo = config.customTypeParams.toDriver;\n    this.mapFrom = config.customTypeParams.fromDriver;\n  }\n  getSQLType() {\n    return this.sqlName;\n  }\n  mapFromDriverValue(value) {\n    return typeof this.mapFrom === \"function\" ? this.mapFrom(value) : value;\n  }\n  mapToDriverValue(value) {\n    return typeof this.mapTo === \"function\" ? this.mapTo(value) : value;\n  }\n}\nfunction customType(customTypeParams) {\n  return (a, b) => {\n    const { name, config } = getColumnNameAndConfig(a, b);\n    return new SQLiteCustomColumnBuilder(\n      name,\n      config,\n      customTypeParams\n    );\n  };\n}\nexport {\n  SQLiteCustomColumn,\n  SQLiteCustomColumnBuilder,\n  customType\n};\n//# sourceMappingURL=custom.js.map","import { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBaseIntegerBuilder\";\n  constructor(name, dataType, columnType) {\n    super(name, dataType, columnType);\n    this.config.autoIncrement = false;\n  }\n  primaryKey(config) {\n    if (config?.autoIncrement) {\n      this.config.autoIncrement = true;\n    }\n    this.config.hasDefault = true;\n    return super.primaryKey();\n  }\n}\nclass SQLiteBaseInteger extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBaseInteger\";\n  autoIncrement = this.config.autoIncrement;\n  getSQLType() {\n    return \"integer\";\n  }\n}\nclass SQLiteIntegerBuilder extends SQLiteBaseIntegerBuilder {\n  static [entityKind] = \"SQLiteIntegerBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"SQLiteInteger\");\n  }\n  build(table) {\n    return new SQLiteInteger(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteInteger extends SQLiteBaseInteger {\n  static [entityKind] = \"SQLiteInteger\";\n}\nclass SQLiteTimestampBuilder extends SQLiteBaseIntegerBuilder {\n  static [entityKind] = \"SQLiteTimestampBuilder\";\n  constructor(name, mode) {\n    super(name, \"date\", \"SQLiteTimestamp\");\n    this.config.mode = mode;\n  }\n  /**\n   * @deprecated Use `default()` with your own expression instead.\n   *\n   * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.\n   */\n  defaultNow() {\n    return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);\n  }\n  build(table) {\n    return new SQLiteTimestamp(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteTimestamp extends SQLiteBaseInteger {\n  static [entityKind] = \"SQLiteTimestamp\";\n  mode = this.config.mode;\n  mapFromDriverValue(value) {\n    if (this.config.mode === \"timestamp\") {\n      return new Date(value * 1e3);\n    }\n    return new Date(value);\n  }\n  mapToDriverValue(value) {\n    const unix = value.getTime();\n    if (this.config.mode === \"timestamp\") {\n      return Math.floor(unix / 1e3);\n    }\n    return unix;\n  }\n}\nclass SQLiteBooleanBuilder extends SQLiteBaseIntegerBuilder {\n  static [entityKind] = \"SQLiteBooleanBuilder\";\n  constructor(name, mode) {\n    super(name, \"boolean\", \"SQLiteBoolean\");\n    this.config.mode = mode;\n  }\n  build(table) {\n    return new SQLiteBoolean(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteBoolean extends SQLiteBaseInteger {\n  static [entityKind] = \"SQLiteBoolean\";\n  mode = this.config.mode;\n  mapFromDriverValue(value) {\n    return Number(value) === 1;\n  }\n  mapToDriverValue(value) {\n    return value ? 1 : 0;\n  }\n}\nfunction integer(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"timestamp\" || config?.mode === \"timestamp_ms\") {\n    return new SQLiteTimestampBuilder(name, config.mode);\n  }\n  if (config?.mode === \"boolean\") {\n    return new SQLiteBooleanBuilder(name, config.mode);\n  }\n  return new SQLiteIntegerBuilder(name);\n}\nconst int = integer;\nexport {\n  SQLiteBaseInteger,\n  SQLiteBaseIntegerBuilder,\n  SQLiteBoolean,\n  SQLiteBooleanBuilder,\n  SQLiteInteger,\n  SQLiteIntegerBuilder,\n  SQLiteTimestamp,\n  SQLiteTimestampBuilder,\n  int,\n  integer\n};\n//# sourceMappingURL=integer.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteNumericBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteNumericBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"SQLiteNumeric\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteNumeric(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteNumeric extends SQLiteColumn {\n  static [entityKind] = \"SQLiteNumeric\";\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    return String(value);\n  }\n  getSQLType() {\n    return \"numeric\";\n  }\n}\nclass SQLiteNumericNumberBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteNumericNumberBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"SQLiteNumericNumber\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteNumericNumber(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteNumericNumber extends SQLiteColumn {\n  static [entityKind] = \"SQLiteNumericNumber\";\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") return value;\n    return Number(value);\n  }\n  mapToDriverValue = String;\n  getSQLType() {\n    return \"numeric\";\n  }\n}\nclass SQLiteNumericBigIntBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteNumericBigIntBuilder\";\n  constructor(name) {\n    super(name, \"bigint\", \"SQLiteNumericBigInt\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteNumericBigInt(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteNumericBigInt extends SQLiteColumn {\n  static [entityKind] = \"SQLiteNumericBigInt\";\n  mapFromDriverValue = BigInt;\n  mapToDriverValue = String;\n  getSQLType() {\n    return \"numeric\";\n  }\n}\nfunction numeric(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  const mode = config?.mode;\n  return mode === \"number\" ? new SQLiteNumericNumberBuilder(name) : mode === \"bigint\" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);\n}\nexport {\n  SQLiteNumeric,\n  SQLiteNumericBigInt,\n  SQLiteNumericBigIntBuilder,\n  SQLiteNumericBuilder,\n  SQLiteNumericNumber,\n  SQLiteNumericNumberBuilder,\n  numeric\n};\n//# sourceMappingURL=numeric.js.map","import { entityKind } from \"../../entity.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteRealBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteRealBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"SQLiteReal\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteReal(table, this.config);\n  }\n}\nclass SQLiteReal extends SQLiteColumn {\n  static [entityKind] = \"SQLiteReal\";\n  getSQLType() {\n    return \"real\";\n  }\n}\nfunction real(name) {\n  return new SQLiteRealBuilder(name ?? \"\");\n}\nexport {\n  SQLiteReal,\n  SQLiteRealBuilder,\n  real\n};\n//# sourceMappingURL=real.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteTextBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteTextBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"SQLiteText\");\n    this.config.enumValues = config.enum;\n    this.config.length = config.length;\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteText(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteText extends SQLiteColumn {\n  static [entityKind] = \"SQLiteText\";\n  enumValues = this.config.enumValues;\n  length = this.config.length;\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return `text${this.config.length ? `(${this.config.length})` : \"\"}`;\n  }\n}\nclass SQLiteTextJsonBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteTextJsonBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"SQLiteTextJson\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteTextJson(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteTextJson extends SQLiteColumn {\n  static [entityKind] = \"SQLiteTextJson\";\n  getSQLType() {\n    return \"text\";\n  }\n  mapFromDriverValue(value) {\n    return JSON.parse(value);\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n}\nfunction text(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config.mode === \"json\") {\n    return new SQLiteTextJsonBuilder(name);\n  }\n  return new SQLiteTextBuilder(name, config);\n}\nexport {\n  SQLiteText,\n  SQLiteTextBuilder,\n  SQLiteTextJson,\n  SQLiteTextJsonBuilder,\n  text\n};\n//# sourceMappingURL=text.js.map","import { blob } from \"./blob.js\";\nimport { customType } from \"./custom.js\";\nimport { integer } from \"./integer.js\";\nimport { numeric } from \"./numeric.js\";\nimport { real } from \"./real.js\";\nimport { text } from \"./text.js\";\nfunction getSQLiteColumnBuilders() {\n  return {\n    blob,\n    customType,\n    integer,\n    numeric,\n    real,\n    text\n  };\n}\nexport {\n  getSQLiteColumnBuilders\n};\n//# sourceMappingURL=all.js.map","import { entityKind } from \"../entity.js\";\nimport { Table } from \"../table.js\";\nimport { getSQLiteColumnBuilders } from \"./columns/all.js\";\nconst InlineForeignKeys = Symbol.for(\"drizzle:SQLiteInlineForeignKeys\");\nclass SQLiteTable extends Table {\n  static [entityKind] = \"SQLiteTable\";\n  /** @internal */\n  static Symbol = Object.assign({}, Table.Symbol, {\n    InlineForeignKeys\n  });\n  /** @internal */\n  [Table.Symbol.Columns];\n  /** @internal */\n  [InlineForeignKeys] = [];\n  /** @internal */\n  [Table.Symbol.ExtraConfigBuilder] = void 0;\n}\nfunction sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {\n  const rawTable = new SQLiteTable(name, schema, baseName);\n  const parsedColumns = typeof columns === \"function\" ? columns(getSQLiteColumnBuilders()) : columns;\n  const builtColumns = Object.fromEntries(\n    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {\n      const colBuilder = colBuilderBase;\n      colBuilder.setName(name2);\n      const column = colBuilder.build(rawTable);\n      rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n      return [name2, column];\n    })\n  );\n  const table = Object.assign(rawTable, builtColumns);\n  table[Table.Symbol.Columns] = builtColumns;\n  table[Table.Symbol.ExtraConfigColumns] = builtColumns;\n  if (extraConfig) {\n    table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;\n  }\n  return table;\n}\nconst sqliteTable = (name, columns, extraConfig) => {\n  return sqliteTableBase(name, columns, extraConfig);\n};\nfunction sqliteTableCreator(customizeTableName) {\n  return (name, columns, extraConfig) => {\n    return sqliteTableBase(customizeTableName(name), columns, extraConfig, void 0, name);\n  };\n}\nexport {\n  InlineForeignKeys,\n  SQLiteTable,\n  sqliteTable,\n  sqliteTableCreator\n};\n//# sourceMappingURL=table.js.map","import { entityKind } from \"../entity.js\";\nclass IndexBuilderOn {\n  constructor(name, unique) {\n    this.name = name;\n    this.unique = unique;\n  }\n  static [entityKind] = \"SQLiteIndexBuilderOn\";\n  on(...columns) {\n    return new IndexBuilder(this.name, columns, this.unique);\n  }\n}\nclass IndexBuilder {\n  static [entityKind] = \"SQLiteIndexBuilder\";\n  /** @internal */\n  config;\n  constructor(name, columns, unique) {\n    this.config = {\n      name,\n      columns,\n      unique,\n      where: void 0\n    };\n  }\n  /**\n   * Condition for partial index.\n   */\n  where(condition) {\n    this.config.where = condition;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new Index(this.config, table);\n  }\n}\nclass Index {\n  static [entityKind] = \"SQLiteIndex\";\n  config;\n  constructor(config, table) {\n    this.config = { ...config, table };\n  }\n}\nfunction index(name) {\n  return new IndexBuilderOn(name, false);\n}\nfunction uniqueIndex(name) {\n  return new IndexBuilderOn(name, true);\n}\nexport {\n  Index,\n  IndexBuilder,\n  IndexBuilderOn,\n  index,\n  uniqueIndex\n};\n//# sourceMappingURL=indexes.js.map","import { entityKind } from \"../entity.js\";\nimport { SQLiteTable } from \"./table.js\";\nfunction primaryKey(...config) {\n  if (config[0].columns) {\n    return new PrimaryKeyBuilder(config[0].columns, config[0].name);\n  }\n  return new PrimaryKeyBuilder(config);\n}\nclass PrimaryKeyBuilder {\n  static [entityKind] = \"SQLitePrimaryKeyBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  name;\n  constructor(columns, name) {\n    this.columns = columns;\n    this.name = name;\n  }\n  /** @internal */\n  build(table) {\n    return new PrimaryKey(table, this.columns, this.name);\n  }\n}\nclass PrimaryKey {\n  constructor(table, columns, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name;\n  }\n  static [entityKind] = \"SQLitePrimaryKey\";\n  columns;\n  name;\n  getName() {\n    return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join(\"_\")}_pk`;\n  }\n}\nexport {\n  PrimaryKey,\n  PrimaryKeyBuilder,\n  primaryKey\n};\n//# sourceMappingURL=primary-keys.js.map","import { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/config.ts\nlet sink;\nfunction configureTracing(options) {\n\tsink = options.sink;\n}\nfunction getTracingSink() {\n\treturn sink;\n}\nfunction resetTracingForTests() {\n\tsink = void 0;\n}\n//#endregion\n//#region src/context.ts\nconst traceContextStorage = new AsyncLocalStorage();\nfunction getTraceContext() {\n\treturn traceContextStorage.getStore();\n}\nfunction runWithTraceContext(context, fn) {\n\treturn traceContextStorage.run(context, fn);\n}\n//#endregion\n//#region src/serialize.ts\nfunction formatConsoleArg(value) {\n\tif (typeof value === \"string\") return value;\n\tif (value instanceof Error) return value.stack ?? value.message;\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\nfunction serializeConsoleArgs(args) {\n\tif (args.length === 0) return { message: \"\" };\n\tconst [first, ...rest] = args;\n\tconst message = formatConsoleArg(first);\n\tif (rest.length === 0) return { message };\n\tif (rest.length === 1) return {\n\t\tmessage,\n\t\tdata: rest[0]\n\t};\n\treturn {\n\t\tmessage,\n\t\tdata: rest\n\t};\n}\nfunction summarizePayload(payload) {\n\tif (payload === void 0) return;\n\ttry {\n\t\tconst serialized = JSON.stringify(payload);\n\t\tif (serialized.length <= 500) return payload;\n\t\treturn {\n\t\t\ttruncated: true,\n\t\t\tlength: serialized.length,\n\t\t\tpreview: serialized.slice(0, 500)\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\ttruncated: true,\n\t\t\tpreview: String(payload).slice(0, 500)\n\t\t};\n\t}\n}\n//#endregion\n//#region src/console.ts\nconst CONSOLE_LEVELS = [\n\t\"log\",\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"error\"\n];\nfunction mapConsoleLevel(level) {\n\tif (level === \"log\") return \"info\";\n\treturn level;\n}\nasync function captureConsole(fn) {\n\tconst originals = /* @__PURE__ */ new Map();\n\tfor (const level of CONSOLE_LEVELS) {\n\t\toriginals.set(level, console[level].bind(console));\n\t\tconsole[level] = (...args) => {\n\t\t\toriginals.get(level)?.(...args);\n\t\t\tconst sink = getTracingSink();\n\t\t\tconst context = getTraceContext();\n\t\t\tif (!sink || !context) return;\n\t\t\tconst { message, data } = serializeConsoleArgs(args);\n\t\t\tsink.appendLog({\n\t\t\t\ttraceId: context.traceId,\n\t\t\t\tspanId: context.spanId,\n\t\t\t\tlevel: mapConsoleLevel(level),\n\t\t\t\tmessage,\n\t\t\t\tdata,\n\t\t\t\tsource: \"console\",\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t});\n\t\t};\n\t}\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\tfor (const level of CONSOLE_LEVELS) {\n\t\t\tconst original = originals.get(level);\n\t\t\tif (original) console[level] = original;\n\t\t}\n\t}\n}\n//#endregion\n//#region src/log.ts\nasync function logSystem(level, message, data) {\n\tconst sink = getTracingSink();\n\tconst context = getTraceContext();\n\tif (!sink || !context) return;\n\tawait sink.appendLog({\n\t\ttraceId: context.traceId,\n\t\tspanId: context.spanId,\n\t\tlevel,\n\t\tmessage,\n\t\tdata,\n\t\tsource: \"system\",\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\n//#endregion\n//#region src/span.ts\nfunction serializeSpanError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\nasync function withSpan(input, fn) {\n\tconst sink = getTracingSink();\n\tif (!sink) return await fn();\n\tconst parent = getTraceContext();\n\tconst spanId = input.spanId ?? crypto.randomUUID();\n\tconst traceId = input.traceId ?? parent?.traceId ?? spanId;\n\tconst parentSpanId = input.parentSpanId ?? parent?.spanId;\n\tconst startedAt = /* @__PURE__ */ new Date();\n\tawait sink.openSpan({\n\t\tid: spanId,\n\t\ttraceId,\n\t\tparentSpanId,\n\t\tkind: input.kind,\n\t\trefId: input.refId,\n\t\tname: input.name,\n\t\tmetadata: input.metadata,\n\t\tstartedAt\n\t});\n\tconst context = {\n\t\ttraceId,\n\t\tspanId,\n\t\tparentSpanId\n\t};\n\ttry {\n\t\tconst result = await runWithTraceContext(context, () => fn());\n\t\tawait sink.closeSpan(spanId, \"ok\", /* @__PURE__ */ new Date());\n\t\treturn result;\n\t} catch (error) {\n\t\tawait sink.closeSpan(spanId, \"error\", /* @__PURE__ */ new Date(), serializeSpanError(error));\n\t\tthrow error;\n\t}\n}\nfunction isSpanActive() {\n\treturn getTraceContext() !== void 0;\n}\n//#endregion\nexport { captureConsole, configureTracing, getTraceContext, isSpanActive, logSystem, resetTracingForTests, runWithTraceContext, summarizePayload, withSpan };\n\n//# sourceMappingURL=index.mjs.map","import { createRequire } from \"node:module\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { doublePrecision, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, real, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from \"drizzle-orm/sqlite-core\";\nimport { and, and as and$1, asc, count, desc, eq, eq as eq$1, gt, inArray, inArray as inArray$1, isNotNull, isNull, lt, lte, max, max as max$1, ne, notInArray, or, sql, sql as sql$1 } from \"drizzle-orm\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport SqliteClient from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { readMigrationFiles } from \"drizzle-orm/migrator\";\nimport { fileURLToPath } from \"node:url\";\nimport { migrate } from \"drizzle-orm/better-sqlite3/migrator\";\nimport { getTraceContext } from \"@keystrokehq/tracing\";\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\nimport { buildCredentialInstanceLabel, deriveCredentialInstanceSlug, displayCredentialAppName, resolveUniqueCredentialInstanceLabel } from \"@keystrokehq/shared\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/config/constants.ts\n/** Used when `DATABASE_URL` is unset and `initDatabase({ url })` is omitted. */\nconst DEFAULT_DATABASE_URL = \"file:./data/dev.db\";\nconst tenantScopeStorage = new AsyncLocalStorage();\nfunction runWithTenantScope(tenantId, fn) {\n\treturn tenantScopeStorage.run(tenantId, fn);\n}\nfunction getServerTenantScopeId() {\n\treturn tenantScopeStorage.getStore() ?? process.env.TENANT_ID?.trim() ?? \"default\";\n}\n//#endregion\n//#region src/config/project-scope.ts\n/** Default project id for local single-project dev. */\nconst DEFAULT_PROJECT_ID = \"default\";\nconst projectScopeStorage = new AsyncLocalStorage();\nfunction runWithProjectScope(projectId, fn) {\n\treturn projectScopeStorage.run(projectId, fn);\n}\nfunction getBoundProjectScopeId() {\n\treturn projectScopeStorage.getStore();\n}\nfunction getProjectScopeId() {\n\treturn getBoundProjectScopeId() ?? \"default\";\n}\n//#endregion\n//#region src/config/postgres-url.ts\nconst POSTGRES_ENV_KEYS = [\n\t\"POSTGRES_HOST\",\n\t\"POSTGRES_PORT\",\n\t\"POSTGRES_DB\",\n\t\"POSTGRES_USER\",\n\t\"POSTGRES_PASSWORD\"\n];\nfunction readEnv(env, key) {\n\treturn env[key]?.trim() || void 0;\n}\nfunction readPostgresSsl(env) {\n\tconst value = readEnv(env, \"POSTGRES_SSL\")?.toLowerCase();\n\treturn value === \"true\" || value === \"1\" || value === \"yes\";\n}\nfunction readPostgresSslFromUrl(url) {\n\ttry {\n\t\tconst sslmode = new URL(url.replace(/^postgresql:/i, \"postgres:\")).searchParams.get(\"sslmode\")?.toLowerCase();\n\t\treturn sslmode === \"require\" || sslmode === \"verify-ca\" || sslmode === \"verify-full\";\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction resolvePostgresSsl(env, url) {\n\treturn readPostgresSsl(env) || (url ? readPostgresSslFromUrl(url) : false);\n}\nfunction resolvePostgresBranch(env) {\n\tconst explicit = env.POSTGRES_BRANCH?.trim();\n\tif (explicit) return explicit;\n\tconst platformUser = readEnv(env, \"POSTGRES_USER\") ?? readPostgresUserFromDatabaseUrl(readEnv(env, \"DATABASE_URL\"));\n\tif (!platformUser?.includes(\".\")) return;\n\treturn platformUser.slice(platformUser.lastIndexOf(\".\") + 1) || void 0;\n}\nfunction readPostgresUserFromDatabaseUrl(url) {\n\tif (!url || !/^postgres(ql)?:\\/\\//i.test(url)) return;\n\ttry {\n\t\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\t\treturn decodeURIComponent(parsed.username);\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction applyPostgresSslMode(url) {\n\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\tif (!parsed.searchParams.has(\"sslmode\")) parsed.searchParams.set(\"sslmode\", \"require\");\n\treturn parsed.toString().replace(/^postgres:/i, \"postgresql:\");\n}\nfunction missingPostgresEnvKeys(env) {\n\treturn POSTGRES_ENV_KEYS.filter((key) => readEnv(env, key) === void 0);\n}\n/** Append POSTGRES_BRANCH to bare role names for providers that use user.branch connections. */\nfunction qualifyConnectionUser(user, env = process.env) {\n\tif (user.includes(\".\")) return user;\n\tconst branch = resolvePostgresBranch(env);\n\tif (!branch) return user;\n\treturn `${user}.${branch}`;\n}\nfunction buildPostgresUrl(config) {\n\tconst user = encodeURIComponent(config.user);\n\tconst password = encodeURIComponent(config.password);\n\tconst auth = config.password ? `${user}:${password}` : user;\n\tconst database = encodeURIComponent(config.database).replace(/%2F/g, \"/\");\n\tconst url = `postgresql://${auth}@${config.host}:${config.port}/${database}`;\n\treturn config.ssl ? applyPostgresSslMode(url) : url;\n}\nfunction parsePostgresUrl(url) {\n\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\tconst database = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n\tif (!database) throw new Error(`Postgres URL is missing database name: ${url}`);\n\treturn {\n\t\thost: parsed.hostname,\n\t\tport: parsed.port ? Number(parsed.port) : 5432,\n\t\tdatabase,\n\t\tuser: decodeURIComponent(parsed.username),\n\t\tpassword: decodeURIComponent(parsed.password)\n\t};\n}\nfunction resolvePostgresConfigFromPostgresEnv(env) {\n\tif (missingPostgresEnvKeys(env).length > 0) return;\n\tconst port = Number(readEnv(env, \"POSTGRES_PORT\"));\n\tif (!Number.isFinite(port)) throw new Error(`Invalid POSTGRES_PORT: ${env.POSTGRES_PORT}`);\n\treturn {\n\t\thost: readEnv(env, \"POSTGRES_HOST\"),\n\t\tport,\n\t\tdatabase: readEnv(env, \"POSTGRES_DB\"),\n\t\tuser: readEnv(env, \"POSTGRES_USER\"),\n\t\tpassword: readEnv(env, \"POSTGRES_PASSWORD\"),\n\t\tssl: readPostgresSsl(env)\n\t};\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresConfigFromEnv(env = process.env) {\n\tconst direct = readEnv(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return {\n\t\t...parsePostgresUrl(direct),\n\t\tssl: resolvePostgresSsl(env, direct)\n\t};\n\tconst config = resolvePostgresConfigFromPostgresEnv(env);\n\tif (!config) throw new Error(`Missing required Postgres env vars: ${missingPostgresEnvKeys(env).join(\", \")}`);\n\treturn config;\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresUrlFromEnv(env = process.env) {\n\tconst ssl = readPostgresSsl(env);\n\tconst direct = readEnv(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return ssl ? applyPostgresSslMode(direct) : direct;\n\treturn buildPostgresUrl(resolvePostgresConfigFromEnv(env));\n}\n/**\n* Project runtime — POSTGRES_* only (same env shape as hosted workers).\n* Returns undefined when unset; initDatabase falls back to sqlite DEFAULT_DATABASE_URL.\n* Optional DATABASE_SEARCH_PATH sets the tenant schema search_path.\n*/\nfunction resolveProjectDatabaseUrlFromEnv(env = process.env) {\n\tconst config = resolvePostgresConfigFromPostgresEnv(env);\n\treturn config ? buildPostgresUrl(config) : void 0;\n}\n/** @deprecated Prefer resolveProjectDatabaseUrlFromEnv (project) or resolvePostgresUrlFromEnv (platform). */\nfunction resolveDatabaseUrlFromEnv(env = process.env) {\n\treturn resolveProjectDatabaseUrlFromEnv(env);\n}\n//#endregion\n//#region src/client/request-context.ts\nconst requestHandle = new AsyncLocalStorage();\nfunction getRequestDatabaseHandle() {\n\treturn requestHandle.getStore();\n}\nfunction runWithRequestDatabaseHandle(handle, fn) {\n\treturn requestHandle.run(handle, fn);\n}\n//#endregion\n//#region src/client/context.ts\nlet handle;\nfunction isDatabaseInitialized() {\n\treturn getRequestDatabaseHandle() !== void 0 || handle !== void 0;\n}\nfunction getDatabaseHandle() {\n\tconst scoped = getRequestDatabaseHandle();\n\tif (scoped) return scoped;\n\tif (!handle) throw new Error(\"Database not initialized. Call initDatabase() before getDb().\");\n\treturn handle;\n}\nfunction setDatabaseHandle(next) {\n\thandle = next;\n}\nfunction getDefaultDatabaseHandle() {\n\treturn handle;\n}\nfunction getDbFromContext() {\n\treturn getDatabaseHandle().db;\n}\n//#endregion\n//#region src/connection/pg/driver.ts\nconst require = createRequire(import.meta.url);\n/**\n* Lazily load the native `pg` driver. Keeping this off the module's static import\n* graph means consumers that only reference database helpers/types (e.g. the CLI,\n* which never opens a Postgres pool) never force `pg` into their bundle — it\n* resolves from the runtime image only when a connection is actually created.\n*/\nfunction loadPg() {\n\treturn require(\"pg\");\n}\n/** Lazily load drizzle's node-postgres adapter — it statically imports `pg`. */\nfunction loadDrizzlePg() {\n\treturn require(\"drizzle-orm/node-postgres\");\n}\n//#endregion\n//#region src/schema/bundle.ts\nfunction buildPgSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { pg }]) => [name, pg]));\n}\nfunction buildSqliteSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { sqlite }]) => [name, sqlite]));\n}\n//#endregion\n//#region src/schema/tables/agents.ts\nconst agents = pgTable(\"agents\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\troute: text(\"route\").notNull(),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tmodel: text(\"model\").notNull(),\n\tsystemPrompt: text(\"system_prompt\").notNull(),\n\ttoolCount: integer(\"tool_count\"),\n\tcredentialCount: integer(\"credential_count\"),\n\tappSlugs: jsonb(\"app_slugs\").$type(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"agents_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex(\"agents_project_id_route_idx\").on(table.projectId, table.route)]);\nconst agentsSqlite = sqliteTable(\"agents\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\troute: text$1(\"route\").notNull(),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tmodel: text$1(\"model\").notNull(),\n\tsystemPrompt: text$1(\"system_prompt\").notNull(),\n\ttoolCount: integer$1(\"tool_count\"),\n\tcredentialCount: integer$1(\"credential_count\"),\n\tappSlugs: text$1(\"app_slugs\", { mode: \"json\" }).$type(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"agents_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex$1(\"agents_project_id_route_idx\").on(table.projectId, table.route)]);\n//#endregion\n//#region src/schema/tables/agent-sessions.ts\nconst agentSessions = pgTable(\"agent_sessions\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tagentId: text(\"agent_id\").notNull().references(() => agents.id),\n\tsourceKind: text(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text(\"source_id\"),\n\tparentSpanId: text(\"parent_span_id\"),\n\tranByUserId: text(\"ran_by_user_id\"),\n\ttitle: text(\"title\"),\n\tcanceledAt: timestamp(\"canceled_at\", { withTimezone: true }),\n\ttotalDurationMs: integer(\"total_duration_ms\").notNull().default(0),\n\tliveMessage: jsonb(\"live_message\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [index(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt)]);\nconst agentSessionsSqlite = sqliteTable(\"agent_sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tagentId: text$1(\"agent_id\").notNull().references(() => agentsSqlite.id),\n\tsourceKind: text$1(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text$1(\"source_id\"),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tranByUserId: text$1(\"ran_by_user_id\"),\n\ttitle: text$1(\"title\"),\n\tcanceledAt: integer$1(\"canceled_at\", { mode: \"timestamp_ms\" }),\n\ttotalDurationMs: integer$1(\"total_duration_ms\").notNull().default(0),\n\tliveMessage: text$1(\"live_message\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt)]);\n//#endregion\n//#region src/schema/tables/agent-events.ts\nconst agentEvents = pgTable(\"agent_events\", {\n\tid: text(\"id\").primaryKey(),\n\tsessionId: text(\"session_id\").notNull().references(() => agentSessions.id),\n\tseq: integer(\"seq\").notNull(),\n\teventType: text(\"event_type\").notNull(),\n\tpayload: jsonb(\"payload\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [index(\"agent_events_session_event_seq_idx\").on(table.sessionId, table.eventType, table.seq)]);\nconst agentEventsSqlite = sqliteTable(\"agent_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\tsessionId: text$1(\"session_id\").notNull().references(() => agentSessionsSqlite.id),\n\tseq: integer$1(\"seq\").notNull(),\n\teventType: text$1(\"event_type\").notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"agent_events_session_event_seq_idx\").on(table.sessionId, table.eventType, table.seq)]);\n//#endregion\n//#region src/schema/tables/usage-records.ts\nconst usageRecords = pgTable(\"usage_records\", {\n\tid: text(\"id\").primaryKey(),\n\trunId: text(\"run_id\").notNull(),\n\trunKind: text(\"run_kind\").$type().notNull(),\n\tkind: text(\"kind\").notNull(),\n\tlabel: text(\"label\").notNull(),\n\tquantity: integer(\"quantity\"),\n\tunit: text(\"unit\"),\n\tamount: doublePrecision(\"amount\").notNull(),\n\tmetadata: jsonb(\"metadata\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"usage_records_run_run_kind_idx\").on(table.runId, table.runKind), index(\"usage_records_kind_idx\").on(table.kind)]);\nconst usageRecordsSqlite = sqliteTable(\"usage_records\", {\n\tid: text$1(\"id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull(),\n\trunKind: text$1(\"run_kind\").$type().notNull(),\n\tkind: text$1(\"kind\").notNull(),\n\tlabel: text$1(\"label\").notNull(),\n\tquantity: integer$1(\"quantity\"),\n\tunit: text$1(\"unit\"),\n\tamount: real(\"amount\").notNull(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"usage_records_run_run_kind_idx\").on(table.runId, table.runKind), index$1(\"usage_records_kind_idx\").on(table.kind)]);\n//#endregion\n//#region src/schema/tables/triggers.ts\nconst triggers = pgTable(\"triggers\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tkind: text(\"kind\").$type().notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\tmoduleFile: text(\"module_file\").notNull(),\n\torigin: text(\"origin\").$type().notNull().default(\"project\"),\n\tconfig: jsonb(\"config\").$type(),\n\tschedule: text(\"schedule\"),\n\tnextRunAt: timestamp(\"next_run_at\", { withTimezone: true }),\n\tenabled: integer(\"enabled\").notNull().default(1),\n\tlifecycle: jsonb(\"lifecycle\").$type(),\n\tcreatedBySessionId: text(\"created_by_session_id\"),\n\ttriggerHash: text(\"trigger_hash\"),\n\toverviewMarkdown: text(\"overview_markdown\"),\n\toverviewHash: text(\"overview_hash\"),\n\toverviewModel: text(\"overview_model\"),\n\toverviewStatus: text(\"overview_status\").$type().notNull().default(\"idle\"),\n\toverviewGeneratedAt: timestamp(\"overview_generated_at\", { withTimezone: true }),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"triggers_project_id_slug_idx\").on(table.projectId, table.slug), index(\"triggers_next_run_at_enabled_idx\").on(table.nextRunAt, table.enabled)]);\nconst triggersSqlite = sqliteTable(\"triggers\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tkind: text$1(\"kind\").$type().notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\torigin: text$1(\"origin\").$type().notNull().default(\"project\"),\n\tconfig: text$1(\"config\", { mode: \"json\" }).$type(),\n\tschedule: text$1(\"schedule\"),\n\tnextRunAt: integer$1(\"next_run_at\", { mode: \"timestamp_ms\" }),\n\tenabled: integer$1(\"enabled\").notNull().default(1),\n\tlifecycle: text$1(\"lifecycle\", { mode: \"json\" }).$type(),\n\tcreatedBySessionId: text$1(\"created_by_session_id\"),\n\ttriggerHash: text$1(\"trigger_hash\"),\n\toverviewMarkdown: text$1(\"overview_markdown\"),\n\toverviewHash: text$1(\"overview_hash\"),\n\toverviewModel: text$1(\"overview_model\"),\n\toverviewStatus: text$1(\"overview_status\").$type().notNull().default(\"idle\"),\n\toverviewGeneratedAt: integer$1(\"overview_generated_at\", { mode: \"timestamp_ms\" }),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"triggers_project_id_slug_idx\").on(table.projectId, table.slug), index$1(\"triggers_next_run_at_enabled_idx\").on(table.nextRunAt, table.enabled)]);\n//#endregion\n//#region src/schema/tables/trigger-attachments.ts\nconst triggerAttachments = pgTable(\"trigger_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\ttriggerId: text(\"trigger_id\").notNull().references(() => triggers.id),\n\tslug: text(\"slug\").notNull(),\n\ttargetKind: text(\"target_kind\").$type().notNull().default(\"workflow\"),\n\tworkflowSlug: text(\"workflow_slug\"),\n\tagentSlug: text(\"agent_slug\"),\n\tprompt: text(\"prompt\"),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdisabledAt: timestamp(\"disabled_at\", { withTimezone: true }),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst triggerAttachmentsSqlite = sqliteTable(\"trigger_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttriggerId: text$1(\"trigger_id\").notNull().references(() => triggersSqlite.id),\n\tslug: text$1(\"slug\").notNull(),\n\ttargetKind: text$1(\"target_kind\").$type().notNull().default(\"workflow\"),\n\tworkflowSlug: text$1(\"workflow_slug\"),\n\tagentSlug: text$1(\"agent_slug\"),\n\tprompt: text$1(\"prompt\"),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdisabledAt: integer$1(\"disabled_at\", { mode: \"timestamp_ms\" }),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/trigger-runs.ts\nconst triggerRuns = pgTable(\"trigger_runs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\ttriggerId: text(\"trigger_id\").notNull().references(() => triggers.id),\n\tsourcePath: text(\"source_path\"),\n\ttriggerType: text(\"trigger_type\").$type().notNull(),\n\toutcome: text(\"outcome\").$type().notNull().default(\"dispatched\"),\n\treason: text(\"reason\").$type(),\n\tdetail: text(\"detail\"),\n\tpayload: jsonb(\"payload\"),\n\ttriggeredAt: timestamp(\"triggered_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"trigger_runs_project_trigger_triggered_idx\").on(table.projectId, table.triggerId, table.triggeredAt), index(\"trigger_runs_project_triggered_idx\").on(table.projectId, table.triggeredAt)]);\nconst triggerRunsSqlite = sqliteTable(\"trigger_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttriggerId: text$1(\"trigger_id\").notNull().references(() => triggersSqlite.id),\n\tsourcePath: text$1(\"source_path\"),\n\ttriggerType: text$1(\"trigger_type\").$type().notNull(),\n\toutcome: text$1(\"outcome\").$type().notNull().default(\"dispatched\"),\n\treason: text$1(\"reason\").$type(),\n\tdetail: text$1(\"detail\"),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\ttriggeredAt: integer$1(\"triggered_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"trigger_runs_project_trigger_triggered_idx\").on(table.projectId, table.triggerId, table.triggeredAt), index$1(\"trigger_runs_project_triggered_idx\").on(table.projectId, table.triggeredAt)]);\n//#endregion\n//#region src/schema/tables/workflow-subscriptions.ts\nconst workflowSubscriptions = pgTable(\"workflow_subscriptions\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tworkflowSlug: text(\"workflow_slug\").notNull(),\n\tuserId: text(\"user_id\").notNull(),\n\tenabled: integer(\"enabled\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId)]);\nconst workflowSubscriptionsSqlite = sqliteTable(\"workflow_subscriptions\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tworkflowSlug: text$1(\"workflow_slug\").notNull(),\n\tuserId: text$1(\"user_id\").notNull(),\n\tenabled: integer$1(\"enabled\", { mode: \"boolean\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId)]);\n//#endregion\n//#region src/schema/tables/workflow-runs.ts\nconst workflowRuns = pgTable(\"workflow_runs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tworkflowSlug: text(\"workflow_slug\").notNull(),\n\tattachmentId: text(\"attachment_id\").references(() => triggerAttachments.id),\n\tsubscriptionId: text(\"subscription_id\").references(() => workflowSubscriptions.id),\n\ttriggerRunId: text(\"trigger_run_id\").references(() => triggerRuns.id),\n\tparentWorkflowRunId: text(\"parent_workflow_run_id\"),\n\tparentSpanId: text(\"parent_span_id\"),\n\tsourceKind: text(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text(\"source_id\"),\n\tranByUserId: text(\"ran_by_user_id\"),\n\tstatus: text(\"status\").$type().notNull(),\n\ttrigger: text(\"trigger\").$type().notNull(),\n\ttriggeredAt: timestamp(\"triggered_at\", { withTimezone: true }).notNull(),\n\tstartedAt: timestamp(\"started_at\", { withTimezone: true }),\n\tfinishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n\tinput: jsonb(\"input\"),\n\toutput: jsonb(\"output\"),\n\terror: jsonb(\"error\")\n}, (table) => [index(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt)]);\nconst workflowRunsSqlite = sqliteTable(\"workflow_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tworkflowSlug: text$1(\"workflow_slug\").notNull(),\n\tattachmentId: text$1(\"attachment_id\").references(() => triggerAttachmentsSqlite.id),\n\tsubscriptionId: text$1(\"subscription_id\").references(() => workflowSubscriptionsSqlite.id),\n\ttriggerRunId: text$1(\"trigger_run_id\").references(() => triggerRunsSqlite.id),\n\tparentWorkflowRunId: text$1(\"parent_workflow_run_id\"),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tsourceKind: text$1(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text$1(\"source_id\"),\n\tranByUserId: text$1(\"ran_by_user_id\"),\n\tstatus: text$1(\"status\").$type().notNull(),\n\ttrigger: text$1(\"trigger\").$type().notNull(),\n\ttriggeredAt: integer$1(\"triggered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tstartedAt: integer$1(\"started_at\", { mode: \"timestamp_ms\" }),\n\tfinishedAt: integer$1(\"finished_at\", { mode: \"timestamp_ms\" }),\n\tinput: text$1(\"input\", { mode: \"json\" }),\n\toutput: text$1(\"output\", { mode: \"json\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n}, (table) => [index$1(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt)]);\n//#endregion\n//#region src/schema/tables/workflow-events.ts\n/**\n* Append-only durable execution log. One row per workflow lifecycle transition.\n* Replay reads these in `seq` order and short-circuits already-completed primitives.\n*/\nconst workflowEvents = pgTable(\"workflow_events\", {\n\tid: text(\"id\").primaryKey(),\n\trunId: text(\"run_id\").notNull().references(() => workflowRuns.id),\n\tprojectId: text(\"project_id\").notNull(),\n\tseq: integer(\"seq\").notNull(),\n\ttype: text(\"type\").$type().notNull(),\n\tcorrelationId: text(\"correlation_id\"),\n\tdata: jsonb(\"data\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tuniqueIndex(\"workflow_events_run_id_seq_unique\").on(table.runId, table.seq),\n\tindex(\"workflow_events_run_id_type_idx\").on(table.runId, table.type),\n\tindex(\"workflow_events_correlation_id_idx\").on(table.correlationId)\n]);\nconst workflowEventsSqlite = sqliteTable(\"workflow_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull().references(() => workflowRunsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tseq: integer$1(\"seq\").notNull(),\n\ttype: text$1(\"type\").$type().notNull(),\n\tcorrelationId: text$1(\"correlation_id\"),\n\tdata: text$1(\"data\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tuniqueIndex$1(\"workflow_events_run_id_seq_unique\").on(table.runId, table.seq),\n\tindex$1(\"workflow_events_run_id_type_idx\").on(table.runId, table.type),\n\tindex$1(\"workflow_events_correlation_id_idx\").on(table.correlationId)\n]);\n//#endregion\n//#region src/schema/tables/workflow-hooks.ts\nconst workflowHooks = pgTable(\"workflow_hooks\", {\n\thookId: text(\"hook_id\").primaryKey(),\n\trunId: text(\"run_id\").notNull().references(() => workflowRuns.id),\n\tprojectId: text(\"project_id\").notNull(),\n\ttoken: text(\"token\").notNull(),\n\tcorrelationId: text(\"correlation_id\").notNull(),\n\tstatus: text(\"status\").$type().notNull(),\n\tschema: jsonb(\"schema\"),\n\tpayload: jsonb(\"payload\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tresumedAt: timestamp(\"resumed_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"workflow_hooks_token_unique\").on(table.token), index(\"workflow_hooks_run_id_idx\").on(table.runId)]);\nconst workflowHooksSqlite = sqliteTable(\"workflow_hooks\", {\n\thookId: text$1(\"hook_id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull().references(() => workflowRunsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttoken: text$1(\"token\").notNull(),\n\tcorrelationId: text$1(\"correlation_id\").notNull(),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tschema: text$1(\"schema\", { mode: \"json\" }),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tresumedAt: integer$1(\"resumed_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"workflow_hooks_token_unique\").on(table.token), index$1(\"workflow_hooks_run_id_idx\").on(table.runId)]);\n//#endregion\n//#region src/schema/tables/credential-instances.ts\nconst credentialInstances = pgTable(\"credential_instances\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tappSlug: text(\"app_slug\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tscopeType: text(\"scope_type\").$type().notNull(),\n\tscopeId: text(\"scope_id\"),\n\tlabel: text(\"label\"),\n\tisDefault: integer(\"is_default\").notNull(),\n\tauthKind: text(\"auth_kind\").$type().notNull(),\n\tciphertext: text(\"ciphertext\"),\n\tconnectionId: text(\"connection_id\"),\n\t/** MCP entity id that owns connection_id when multiple scopes share one connection. */\n\tsharedConnectionId: text(\"shared_connection_id\"),\n\tgrantedScopes: jsonb(\"granted_scopes\").$type(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tlastUsedAt: timestamp(\"last_used_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug), index(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId)]);\nconst credentialInstancesSqlite = sqliteTable(\"credential_instances\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tappSlug: text$1(\"app_slug\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tscopeType: text$1(\"scope_type\").$type().notNull(),\n\tscopeId: text$1(\"scope_id\"),\n\tlabel: text$1(\"label\"),\n\tisDefault: integer$1(\"is_default\", { mode: \"boolean\" }).notNull(),\n\tauthKind: text$1(\"auth_kind\").$type().notNull(),\n\tciphertext: text$1(\"ciphertext\"),\n\tconnectionId: text$1(\"connection_id\"),\n\t/** MCP entity id that owns connection_id when multiple scopes share one connection. */\n\tsharedConnectionId: text$1(\"shared_connection_id\"),\n\tgrantedScopes: text$1(\"granted_scopes\", { mode: \"json\" }).$type(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tlastUsedAt: integer$1(\"last_used_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug), index$1(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId)]);\n//#endregion\n//#region src/schema/tables/credential-assignments.ts\nconst credentialAssignments = pgTable(\"credential_assignments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\ttargetType: text(\"target_type\").$type().notNull(),\n\ttargetKey: text(\"target_key\").notNull(),\n\t/** '*' = wildcard; else runtime consumer id (step correlation id or tool slug). */\n\tconsumerId: text(\"consumer_id\").notNull(),\n\tcredentialSlug: text(\"credential_slug\").notNull(),\n\tinstanceId: text(\"instance_id\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug)]);\nconst credentialAssignmentsSqlite = sqliteTable(\"credential_assignments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttargetType: text$1(\"target_type\").$type().notNull(),\n\ttargetKey: text$1(\"target_key\").notNull(),\n\tconsumerId: text$1(\"consumer_id\").notNull(),\n\tcredentialSlug: text$1(\"credential_slug\").notNull(),\n\tinstanceId: text$1(\"instance_id\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug)]);\n//#endregion\n//#region src/schema/tables/jobs.ts\nconst jobs = pgTable(\"jobs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tkind: text(\"kind\").$type().notNull(),\n\ttargetId: text(\"target_id\").notNull(),\n\trunId: text(\"run_id\").notNull(),\n\ttrigger: text(\"trigger\").$type().notNull(),\n\tpayload: jsonb(\"payload\"),\n\tstatus: text(\"status\").$type().notNull(),\n\tscheduledAt: timestamp(\"scheduled_at\", { withTimezone: true }).notNull(),\n\tattempt: integer(\"attempt\").notNull(),\n\tmaxAttempts: integer(\"max_attempts\").notNull(),\n\tleasedBy: text(\"leased_by\"),\n\tleaseExpiresAt: timestamp(\"lease_expires_at\", { withTimezone: true }),\n\tcompletedAt: timestamp(\"completed_at\", { withTimezone: true }),\n\terror: jsonb(\"error\")\n});\nconst jobsSqlite = sqliteTable(\"jobs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tkind: text$1(\"kind\").$type().notNull(),\n\ttargetId: text$1(\"target_id\").notNull(),\n\trunId: text$1(\"run_id\").notNull(),\n\ttrigger: text$1(\"trigger\").$type().notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tscheduledAt: integer$1(\"scheduled_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tattempt: integer$1(\"attempt\").notNull(),\n\tmaxAttempts: integer$1(\"max_attempts\").notNull(),\n\tleasedBy: text$1(\"leased_by\"),\n\tleaseExpiresAt: integer$1(\"lease_expires_at\", { mode: \"timestamp_ms\" }),\n\tcompletedAt: integer$1(\"completed_at\", { mode: \"timestamp_ms\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n});\n//#endregion\n//#region src/schema/tables/gateway-attachments.ts\nconst gatewayAttachments = pgTable(\"gateway_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tagentSlug: text(\"agent_slug\").notNull(),\n\tmoduleFile: text(\"module_file\"),\n\tplatform: text(\"platform\").notNull(),\n\tteamId: text(\"team_id\"),\n\tchannelId: text(\"channel_id\").notNull(),\n\tsource: jsonb(\"source\").$type().notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`)]);\nconst gatewayAttachmentsSqlite = sqliteTable(\"gateway_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tagentSlug: text$1(\"agent_slug\").notNull(),\n\tmoduleFile: text$1(\"module_file\"),\n\tplatform: text$1(\"platform\").notNull(),\n\tteamId: text$1(\"team_id\"),\n\tchannelId: text$1(\"channel_id\").notNull(),\n\tsource: text$1(\"source\", { mode: \"json\" }).$type().notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex$1(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`)]);\nfunction gatewayAttachmentKeyForChannel(platform, channelId) {\n\treturn `${platform}:${channelId}`;\n}\n//#endregion\n//#region src/schema/tables/gateway-thread-sessions.ts\nconst gatewayThreadSessions = pgTable(\"gateway_thread_sessions\", {\n\tthreadId: text(\"thread_id\").primaryKey(),\n\tagentId: text(\"agent_id\").notNull().references(() => agents.id),\n\tsessionId: text(\"session_id\").notNull().references(() => agentSessions.id),\n\tattachmentId: text(\"attachment_id\").notNull().references(() => gatewayAttachments.id),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n});\nconst gatewayThreadSessionsSqlite = sqliteTable(\"gateway_thread_sessions\", {\n\tthreadId: text$1(\"thread_id\").primaryKey(),\n\tagentId: text$1(\"agent_id\").notNull().references(() => agentsSqlite.id),\n\tsessionId: text$1(\"session_id\").notNull().references(() => agentSessionsSqlite.id),\n\tattachmentId: text$1(\"attachment_id\").notNull().references(() => gatewayAttachmentsSqlite.id),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/trace-spans.ts\nconst traceSpans = pgTable(\"trace_spans\", {\n\tid: text(\"id\").primaryKey(),\n\ttraceId: text(\"trace_id\").notNull(),\n\tparentSpanId: text(\"parent_span_id\"),\n\tkind: text(\"kind\").$type().notNull(),\n\trefId: text(\"ref_id\").notNull(),\n\tname: text(\"name\").notNull(),\n\tstatus: text(\"status\").$type().notNull(),\n\tstartedAt: timestamp(\"started_at\", { withTimezone: true }).notNull(),\n\tfinishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n\tmetadata: jsonb(\"metadata\"),\n\terror: jsonb(\"error\")\n});\nconst traceSpansSqlite = sqliteTable(\"trace_spans\", {\n\tid: text$1(\"id\").primaryKey(),\n\ttraceId: text$1(\"trace_id\").notNull(),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tkind: text$1(\"kind\").$type().notNull(),\n\trefId: text$1(\"ref_id\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tstartedAt: integer$1(\"started_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tfinishedAt: integer$1(\"finished_at\", { mode: \"timestamp_ms\" }),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n});\n//#endregion\n//#region src/schema/tables/trace-logs.ts\nconst traceLogs = pgTable(\"trace_logs\", {\n\tid: text(\"id\").primaryKey(),\n\ttraceId: text(\"trace_id\").notNull(),\n\tspanId: text(\"span_id\").notNull().references(() => traceSpans.id),\n\tseq: integer(\"seq\").notNull(),\n\tlevel: text(\"level\").$type().notNull(),\n\tmessage: text(\"message\").notNull(),\n\tdata: jsonb(\"data\"),\n\tsource: text(\"source\").$type().notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq), index(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq)]);\nconst traceLogsSqlite = sqliteTable(\"trace_logs\", {\n\tid: text$1(\"id\").primaryKey(),\n\ttraceId: text$1(\"trace_id\").notNull(),\n\tspanId: text$1(\"span_id\").notNull().references(() => traceSpansSqlite.id),\n\tseq: integer$1(\"seq\").notNull(),\n\tlevel: text$1(\"level\").$type().notNull(),\n\tmessage: text$1(\"message\").notNull(),\n\tdata: text$1(\"data\", { mode: \"json\" }),\n\tsource: text$1(\"source\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq), index$1(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq)]);\n//#endregion\n//#region src/schema/tables/skills.ts\nconst skills = pgTable(\"skills\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"skills_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst skillsSqlite = sqliteTable(\"skills\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"skills_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/workflows.ts\nconst workflows = pgTable(\"workflows\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\").notNull(),\n\tdescription: text(\"description\").notNull(),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tsubscribable: integer(\"subscribable\").notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true }),\n\trunInputValues: jsonb(\"run_input_values\").$type(),\n\tcanvasAnnotationsJson: jsonb(\"canvas_annotations_json\").$type(),\n\tcanvasAnnotationsHash: text(\"canvas_annotations_hash\"),\n\tcanvasAnnotationsModel: text(\"canvas_annotations_model\"),\n\tcanvasAnnotationsStatus: text(\"canvas_annotations_status\").$type().notNull().default(\"idle\"),\n\tcanvasAnnotationsGeneratedAt: timestamp(\"canvas_annotations_generated_at\", { withTimezone: true }),\n\toverviewSummary: text(\"overview_summary\"),\n\toverviewPhasesJson: jsonb(\"overview_phases_json\").$type(),\n\toverviewHash: text(\"overview_hash\"),\n\toverviewModel: text(\"overview_model\"),\n\toverviewStatus: text(\"overview_status\").$type().notNull().default(\"idle\"),\n\toverviewGeneratedAt: timestamp(\"overview_generated_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst workflowsSqlite = sqliteTable(\"workflows\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tdescription: text$1(\"description\").notNull(),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tsubscribable: integer$1(\"subscribable\", { mode: \"boolean\" }).notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" }),\n\trunInputValues: text$1(\"run_input_values\", { mode: \"json\" }).$type(),\n\tcanvasAnnotationsJson: text$1(\"canvas_annotations_json\", { mode: \"json\" }).$type(),\n\tcanvasAnnotationsHash: text$1(\"canvas_annotations_hash\"),\n\tcanvasAnnotationsModel: text$1(\"canvas_annotations_model\"),\n\tcanvasAnnotationsStatus: text$1(\"canvas_annotations_status\").$type().notNull().default(\"idle\"),\n\tcanvasAnnotationsGeneratedAt: integer$1(\"canvas_annotations_generated_at\", { mode: \"timestamp_ms\" }),\n\toverviewSummary: text$1(\"overview_summary\"),\n\toverviewPhasesJson: text$1(\"overview_phases_json\", { mode: \"json\" }).$type(),\n\toverviewHash: text$1(\"overview_hash\"),\n\toverviewModel: text$1(\"overview_model\"),\n\toverviewStatus: text$1(\"overview_status\").$type().notNull().default(\"idle\"),\n\toverviewGeneratedAt: integer$1(\"overview_generated_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/resource-activity.ts\nconst resourceActivity = pgTable(\"resource_activity\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tuserId: text(\"user_id\").notNull(),\n\tresourceKind: text(\"resource_kind\").notNull(),\n\tresourceId: text(\"resource_id\").notNull(),\n\tlastOpenedAt: timestamp(\"last_opened_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId), index(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt)]);\nconst resourceActivitySqlite = sqliteTable(\"resource_activity\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull(),\n\tresourceKind: text$1(\"resource_kind\").notNull(),\n\tresourceId: text$1(\"resource_id\").notNull(),\n\tlastOpenedAt: integer$1(\"last_opened_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId), index$1(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt)]);\n//#endregion\n//#region src/schema/registrations.ts\n/**\n* Project server tables — Postgres (hosted) or SQLite (local dev).\n*/\nconst tableRegistry = {\n\tagents: {\n\t\tpg: agents,\n\t\tsqlite: agentsSqlite\n\t},\n\tagentSessions: {\n\t\tpg: agentSessions,\n\t\tsqlite: agentSessionsSqlite\n\t},\n\tagentEvents: {\n\t\tpg: agentEvents,\n\t\tsqlite: agentEventsSqlite\n\t},\n\tusageRecords: {\n\t\tpg: usageRecords,\n\t\tsqlite: usageRecordsSqlite\n\t},\n\ttriggers: {\n\t\tpg: triggers,\n\t\tsqlite: triggersSqlite\n\t},\n\ttriggerAttachments: {\n\t\tpg: triggerAttachments,\n\t\tsqlite: triggerAttachmentsSqlite\n\t},\n\ttriggerRuns: {\n\t\tpg: triggerRuns,\n\t\tsqlite: triggerRunsSqlite\n\t},\n\tworkflowRuns: {\n\t\tpg: workflowRuns,\n\t\tsqlite: workflowRunsSqlite\n\t},\n\tworkflowEvents: {\n\t\tpg: workflowEvents,\n\t\tsqlite: workflowEventsSqlite\n\t},\n\tworkflowHooks: {\n\t\tpg: workflowHooks,\n\t\tsqlite: workflowHooksSqlite\n\t},\n\tcredentialInstances: {\n\t\tpg: credentialInstances,\n\t\tsqlite: credentialInstancesSqlite\n\t},\n\tcredentialAssignments: {\n\t\tpg: credentialAssignments,\n\t\tsqlite: credentialAssignmentsSqlite\n\t},\n\tjobs: {\n\t\tpg: jobs,\n\t\tsqlite: jobsSqlite\n\t},\n\tgatewayAttachments: {\n\t\tpg: gatewayAttachments,\n\t\tsqlite: gatewayAttachmentsSqlite\n\t},\n\tgatewayThreadSessions: {\n\t\tpg: gatewayThreadSessions,\n\t\tsqlite: gatewayThreadSessionsSqlite\n\t},\n\ttraceSpans: {\n\t\tpg: traceSpans,\n\t\tsqlite: traceSpansSqlite\n\t},\n\ttraceLogs: {\n\t\tpg: traceLogs,\n\t\tsqlite: traceLogsSqlite\n\t},\n\tskills: {\n\t\tpg: skills,\n\t\tsqlite: skillsSqlite\n\t},\n\tworkflows: {\n\t\tpg: workflows,\n\t\tsqlite: workflowsSqlite\n\t},\n\tworkflowSubscriptions: {\n\t\tpg: workflowSubscriptions,\n\t\tsqlite: workflowSubscriptionsSqlite\n\t},\n\tresourceActivity: {\n\t\tpg: resourceActivity,\n\t\tsqlite: resourceActivitySqlite\n\t}\n};\nconst schema = buildPgSchema(tableRegistry);\nbuildSqliteSchema(tableRegistry);\n//#endregion\n//#region src/schema/pg.ts\nvar pg_exports = /* @__PURE__ */ __exportAll({\n\tagentEvents: () => agentEvents,\n\tagentSessions: () => agentSessions,\n\tagents: () => agents,\n\tcredentialAssignments: () => credentialAssignments,\n\tcredentialInstances: () => credentialInstances,\n\tgatewayAttachments: () => gatewayAttachments,\n\tgatewayThreadSessions: () => gatewayThreadSessions,\n\tjobs: () => jobs,\n\tresourceActivity: () => resourceActivity,\n\tschema: () => schema,\n\tskills: () => skills,\n\ttraceLogs: () => traceLogs,\n\ttraceSpans: () => traceSpans,\n\ttriggerAttachments: () => triggerAttachments,\n\ttriggerRuns: () => triggerRuns,\n\ttriggers: () => triggers,\n\tusageRecords: () => usageRecords,\n\tworkflowEvents: () => workflowEvents,\n\tworkflowHooks: () => workflowHooks,\n\tworkflowRuns: () => workflowRuns,\n\tworkflowSubscriptions: () => workflowSubscriptions,\n\tworkflows: () => workflows\n});\n//#endregion\n//#region src/connection/pg/db.ts\n/** Inferred from `schema` — `getDb()` and query files use this type. */\nfunction createPgDb(pool) {\n\treturn loadDrizzlePg().drizzle(pool, { schema });\n}\n//#endregion\n//#region src/connection/pg/search-path.ts\nconst SCHEMA_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n/** Drizzle __drizzle_migrations schema — tenant path when set, else public (platform). */\nfunction resolveMigrationsSchema(searchPath) {\n\treturn searchPath ? primarySearchPathSchema(searchPath) : \"public\";\n}\n/** First schema in a comma-separated search_path (the tenant / app schema). */\nfunction primarySearchPathSchema(searchPath) {\n\tconst schema = searchPath.split(\",\")[0]?.trim();\n\tif (!schema || !SCHEMA_IDENT.test(schema)) throw new Error(`Invalid search_path: ${searchPath}`);\n\treturn schema;\n}\nfunction parseSearchPathFromUrl(url) {\n\ttry {\n\t\tconst parsed = new URL(url.replace(/^postgresql:/, \"postgres:\"));\n\t\tconst direct = parsed.searchParams.get(\"search_path\");\n\t\tif (direct) return direct;\n\t\tconst options = parsed.searchParams.get(\"options\");\n\t\tif (!options) return;\n\t\treturn decodeURIComponent(options).match(/search_path[= ]([^,\\s]+(?:,\\s*[^,\\s]+)*)/i)?.[1]?.trim();\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction resolveSearchPath(url, override) {\n\tconst explicit = override?.trim() || process.env.DATABASE_SEARCH_PATH?.trim();\n\tif (explicit) {\n\t\tprimarySearchPathSchema(explicit);\n\t\treturn explicit;\n\t}\n\treturn parseSearchPathFromUrl(url);\n}\n//#endregion\n//#region src/connection/pg/index.ts\nfunction createPgConnection(options) {\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst { Pool } = loadPg();\n\tconst pool = new Pool({\n\t\tconnectionString: options.url,\n\t\tmax: options.max ?? 10,\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath,\n\t\tclose: () => pool.end()\n\t};\n}\n//#endregion\n//#region src/connection/sqlite/configure.ts\n/** Pragmas for on-disk sqlite (WAL, FKs, busy timeout). No-op for `:memory:`. */\nfunction configureSqlite(client, path) {\n\tif (path === \":memory:\" || path.startsWith(\":memory:\")) {\n\t\tclient.pragma(\"foreign_keys = ON\");\n\t\treturn;\n\t}\n\tclient.pragma(\"journal_mode = WAL\");\n\tclient.pragma(\"synchronous = NORMAL\");\n\tclient.pragma(\"foreign_keys = ON\");\n\tclient.pragma(\"busy_timeout = 5000\");\n}\n//#endregion\n//#region src/connection/sqlite/resolve-path.ts\nfunction resolveSqlitePath(url) {\n\tif (url === \":memory:\" || url.startsWith(\":memory:\")) return url;\n\tif (url.startsWith(\"file:\")) return url.slice(5);\n\tif (url.startsWith(\"sqlite:\")) return url.slice(7);\n\treturn url;\n}\n//#endregion\n//#region src/connection/sqlite/index.ts\nfunction createSqliteConnection(options) {\n\tconst path = resolveSqlitePath(options.url);\n\tif (path !== \":memory:\" && !path.startsWith(\":memory:\")) mkdirSync(dirname(path), { recursive: true });\n\tconst client = new SqliteClient(path);\n\tconfigureSqlite(client, path);\n\treturn {\n\t\tdialect: \"sqlite\",\n\t\tdb: drizzle(client, { schema: pg_exports }),\n\t\tclose: () => client.close()\n\t};\n}\n//#endregion\n//#region src/connection/pg/cancel-channel.ts\n/** Postgres LISTEN/NOTIFY pub/sub for a single cancel channel (lowercase identifier, max 63 chars). */\nfunction createPostgresCancelChannel(connectionString, channel) {\n\tconst { Client } = loadPg();\n\treturn {\n\t\tasync publishCancel(runId) {\n\t\t\tconst client = new Client({ connectionString });\n\t\t\tawait client.connect();\n\t\t\ttry {\n\t\t\t\tawait client.query(\"SELECT pg_notify($1, $2)\", [channel, runId]);\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t\tasync subscribeCancel(handler) {\n\t\t\tconst client = new Client({ connectionString });\n\t\t\tawait client.connect();\n\t\t\tawait client.query(`LISTEN ${channel}`);\n\t\t\tconst onNotification = (message) => {\n\t\t\t\tif (message.payload) handler(message.payload);\n\t\t\t};\n\t\t\tclient.on(\"notification\", onNotification);\n\t\t\treturn async () => {\n\t\t\t\tclient.off(\"notification\", onNotification);\n\t\t\t\tawait client.query(`UNLISTEN ${channel}`);\n\t\t\t\tawait client.end();\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/connection/index.ts\nfunction createConnection(options) {\n\tif (options.dialect === \"postgres\") return createPgConnection({\n\t\turl: options.url,\n\t\tmax: options.max,\n\t\tsearchPath: options.searchPath\n\t});\n\treturn createSqliteConnection({ url: options.url });\n}\n//#endregion\n//#region src/connection/pg/pg-ident.ts\nconst PG_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nfunction assertPgIdent(name) {\n\tif (!PG_IDENT.test(name)) throw new Error(`Invalid Postgres identifier: ${name}`);\n}\nfunction quotePgIdent(name) {\n\tassertPgIdent(name);\n\treturn `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n//#endregion\n//#region src/connection/pg/org-scoped-pool.ts\nfunction queryText$1(args) {\n\tconst first = args[0];\n\tif (typeof first === \"string\") return first;\n\treturn first.text;\n}\nfunction normalizeSqlCommand$1(text) {\n\treturn text?.trim().split(/\\s+/)[0]?.toUpperCase();\n}\nfunction isFullRollback$1(text) {\n\treturn text?.trim().toUpperCase() === \"ROLLBACK\";\n}\nfunction buildOrgScopePrologue(role, searchPath) {\n\tconst roleIdent = quotePgIdent(role);\n\tconst schemaIdent = quotePgIdent(primarySearchPathSchema(searchPath));\n\treturn [`SET LOCAL ROLE ${roleIdent}`, `SET LOCAL search_path TO ${schemaIdent}`];\n}\nasync function applyOrgScopePrologue(query, role, searchPath) {\n\tfor (const statement of buildOrgScopePrologue(role, searchPath)) await query(statement);\n}\nfunction bindQuery$1(originalQuery) {\n\treturn (...args) => Promise.resolve(originalQuery(...args));\n}\nfunction createOrgScopedClient(client, role, searchPath) {\n\tconst originalQuery = bindQuery$1(client.query.bind(client));\n\tlet prologueApplied = false;\n\tclient.query = ((...args) => {\n\t\tconst sql = queryText$1(args);\n\t\tconst command = normalizeSqlCommand$1(sql);\n\t\tif (command === \"BEGIN\") return originalQuery(...args).then(async (result) => {\n\t\t\tif (!prologueApplied) {\n\t\t\t\tawait applyOrgScopePrologue(originalQuery, role, searchPath);\n\t\t\t\tprologueApplied = true;\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t\tif (command === \"COMMIT\") {\n\t\t\tprologueApplied = false;\n\t\t\treturn originalQuery(...args);\n\t\t}\n\t\tif (command === \"ROLLBACK\" && isFullRollback$1(sql)) {\n\t\t\tprologueApplied = false;\n\t\t\treturn originalQuery(...args);\n\t\t}\n\t\tif (command === \"ROLLBACK\") return originalQuery(...args);\n\t\treturn originalQuery(...args);\n\t});\n\treturn client;\n}\nfunction createOrgScopedPool(options) {\n\tconst { pool, role, searchPath } = options;\n\tassertOrgScope(role, searchPath);\n\tconst scopedPool = Object.create(pool);\n\tscopedPool.query = (async (...args) => {\n\t\tconst client = await pool.connect();\n\t\tconst query = bindQuery$1(client.query.bind(client));\n\t\ttry {\n\t\t\tawait query(\"BEGIN\");\n\t\t\tawait applyOrgScopePrologue(query, role, searchPath);\n\t\t\tconst result = await query(...args);\n\t\t\tawait query(\"COMMIT\");\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tawait query(\"ROLLBACK\").catch(() => void 0);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclient.release();\n\t\t}\n\t});\n\tscopedPool.connect = ((callback) => {\n\t\tif (callback) return pool.connect((error, client, release) => {\n\t\t\tif (error || !client) {\n\t\t\t\tcallback(error ?? /* @__PURE__ */ new Error(\"failed to connect\"), client, release);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcallback(null, createOrgScopedClient(client, role, searchPath), release);\n\t\t});\n\t\treturn pool.connect().then((client) => createOrgScopedClient(client, role, searchPath));\n\t});\n\treturn scopedPool;\n}\nfunction createOrgScopedHandle(options) {\n\tconst searchPath = primarySearchPathSchema(options.searchPath);\n\tconst scopedPool = createOrgScopedPool({\n\t\t...options,\n\t\tsearchPath\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(scopedPool),\n\t\tpool: scopedPool,\n\t\tsearchPath,\n\t\tclose: async () => void 0\n\t};\n}\nfunction assertOrgScope(role, searchPath) {\n\tif (!role?.trim()) throw new Error(\"Shared-login tenant access requires role\");\n\tif (!searchPath?.trim()) throw new Error(\"Shared-login tenant access requires searchPath\");\n\tquotePgIdent(role);\n\tprimarySearchPathSchema(searchPath);\n}\n//#endregion\n//#region src/dialect/infer.ts\nfunction inferDialect(url, override) {\n\tif (override) return override;\n\tconst lower = url.toLowerCase();\n\tif (lower.startsWith(\"postgres://\") || lower.startsWith(\"postgresql://\")) return \"postgres\";\n\tif (lower.startsWith(\"file:\") || lower.startsWith(\"sqlite:\") || lower === \":memory:\" || lower.startsWith(\":memory:\")) return \"sqlite\";\n\tif (!url.includes(\"://\")) return \"sqlite\";\n\tthrow new Error(`Could not infer database dialect from DATABASE_URL. Set dialect explicitly (got: ${url})`);\n}\n//#endregion\n//#region src/client/pool-cache.ts\nconst IDLE_EVICT_MS = 6e4;\nconst EVICT_INTERVAL_MS = 3e4;\nconst cache = /* @__PURE__ */ new Map();\nlet evictTimer;\nfunction sharedPoolCacheKey(url, max) {\n\treturn `${url}\\0shared-login\\0${max ?? \"\"}`;\n}\nfunction touch(entry) {\n\tentry.lastUsedAt = Date.now();\n}\nfunction ensureEvictTimer() {\n\tif (evictTimer) return;\n\tevictTimer = setInterval(() => {\n\t\tevictIdlePools();\n\t}, EVICT_INTERVAL_MS);\n\tevictTimer.unref?.();\n}\nasync function closeEntry(key, entry) {\n\tcache.delete(key);\n\tawait entry.handle.close();\n}\nasync function evictIdlePools() {\n\tconst now = Date.now();\n\tfor (const [key, entry] of cache) if (entry.refs === 0 && now - entry.lastUsedAt >= IDLE_EVICT_MS) await closeEntry(key, entry);\n}\nasync function acquireProjectDatabasePool(options) {\n\tconst dialect = inferDialect(options.url);\n\tif (dialect !== \"postgres\") {\n\t\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\t\treturn createConnection({\n\t\t\turl: options.url,\n\t\t\tdialect,\n\t\t\tmax: options.max,\n\t\t\tsearchPath\n\t\t});\n\t}\n\tconst role = options.role?.trim();\n\tif (!role) {\n\t\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\t\treturn createConnection({\n\t\t\turl: options.url,\n\t\t\tdialect,\n\t\t\tmax: options.max,\n\t\t\tsearchPath\n\t\t});\n\t}\n\tif (!options.searchPath?.trim()) throw new Error(\"Shared-login tenant access requires role and searchPath\");\n\tconst max = options.max ?? 5;\n\tconst key = sharedPoolCacheKey(options.url, max);\n\tlet entry = cache.get(key);\n\tif (!entry) {\n\t\tentry = {\n\t\t\thandle: createConnection({\n\t\t\t\turl: options.url,\n\t\t\t\tdialect,\n\t\t\t\tmax\n\t\t\t}),\n\t\t\trefs: 0,\n\t\t\tlastUsedAt: Date.now()\n\t\t};\n\t\tcache.set(key, entry);\n\t\tensureEvictTimer();\n\t}\n\tentry.refs += 1;\n\ttouch(entry);\n\tif (entry.handle.dialect !== \"postgres\") {\n\t\tentry.refs = Math.max(0, entry.refs - 1);\n\t\tthrow new Error(\"Shared-login tenant access requires postgres\");\n\t}\n\treturn createOrgScopedHandle({\n\t\tpool: entry.handle.pool,\n\t\trole,\n\t\tsearchPath: options.searchPath\n\t});\n}\nfunction releaseProjectDatabasePool(options) {\n\tif (inferDialect(options.url) !== \"postgres\" || !options.role?.trim()) return;\n\tconst max = options.max ?? 5;\n\tconst key = sharedPoolCacheKey(options.url, max);\n\tconst entry = cache.get(key);\n\tif (!entry) return;\n\tentry.refs = Math.max(0, entry.refs - 1);\n\ttouch(entry);\n}\nasync function closeAllProjectDatabasePools() {\n\tconst entries = [...cache.entries()];\n\tcache.clear();\n\tif (evictTimer) {\n\t\tclearInterval(evictTimer);\n\t\tevictTimer = void 0;\n\t}\n\tawait Promise.all(entries.map(([, entry]) => entry.handle.close()));\n}\n//#endregion\n//#region src/client/close.ts\nasync function closeDatabase() {\n\tif (getRequestDatabaseHandle()) throw new Error(\"closeDatabase() cannot be called inside runWithProjectDatabase()\");\n\tawait closeAllProjectDatabasePools();\n\tconst handle = getDefaultDatabaseHandle();\n\tif (!handle) return;\n\tawait handle.close();\n\tsetDatabaseHandle(void 0);\n}\n//#endregion\n//#region src/migrate/adapt-pg-migrations.ts\n/** Drizzle-kit emits REFERENCES \"public\".\"table\" — strip public so search_path applies. */\nfunction adaptPgMigrationsForSearchPath(migrations) {\n\treturn migrations.map((migration) => ({\n\t\t...migration,\n\t\tsql: migration.sql.map((statement) => statement.replace(/REFERENCES \"public\"\\./gi, \"REFERENCES \"))\n\t}));\n}\n//#endregion\n//#region src/migrate/load-migrations.ts\nfunction loadMigrations(migrationsFolder, embedded) {\n\tif (existsSync(join(migrationsFolder, \"meta\", \"_journal.json\"))) return readMigrationFiles({ migrationsFolder });\n\treturn embedded.map((migration) => ({\n\t\t...migration,\n\t\tsql: [...migration.sql]\n\t}));\n}\n//#endregion\n//#region src/migrate/migrate-pg.ts\nasync function migratePgDatabase(db, config, migrations) {\n\tconst migrator = db;\n\tawait migrator.dialect.migrate(migrations, migrator.session, config);\n}\n//#endregion\n//#region src/migrate/resolve-folder.ts\nfunction resolvePackageRoot() {\n\tlet dir = dirname(fileURLToPath(import.meta.url));\n\tfor (;;) {\n\t\tif (existsSync(join(dir, \"drizzle\", \"sqlite\", \"meta\", \"_journal.json\")) || existsSync(join(dir, \"drizzle\", \"pg\", \"meta\", \"_journal.json\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tthrow new Error(\"Could not resolve @keystrokehq/database package root for migrations\");\n}\nfunction fallbackFolder(...segments) {\n\treturn join(dirname(fileURLToPath(import.meta.url)), ...segments);\n}\nfunction resolveMigrationsFolder(dialect, override) {\n\tif (override) return override;\n\ttry {\n\t\treturn join(resolvePackageRoot(), \"drizzle\", dialect === \"postgres\" ? \"pg\" : \"sqlite\");\n\t} catch {\n\t\treturn fallbackFolder(\"drizzle\", dialect === \"postgres\" ? \"pg\" : \"sqlite\");\n\t}\n}\n//#endregion\n//#region src/migrate/migrations.pg.generated.ts\nconst pgMigrations = [\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"agent_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"event_type\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"agent_sessions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"agents\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"route\\\" text NOT NULL,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"model\\\" text NOT NULL,\\n\t\\\"system_prompt\\\" text NOT NULL,\\n\t\\\"tool_count\\\" integer,\\n\t\\\"credential_count\\\" integer,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"credential_instances\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"scope_type\\\" text NOT NULL,\\n\t\\\"scope_id\\\" text,\\n\t\\\"label\\\" text,\\n\t\\\"is_default\\\" integer NOT NULL,\\n\t\\\"auth_kind\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text,\\n\t\\\"connection_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"gateway_attachments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"agent_slug\\\" text NOT NULL,\\n\t\\\"module_file\\\" text,\\n\t\\\"platform\\\" text NOT NULL,\\n\t\\\"team_id\\\" text,\\n\t\\\"channel_id\\\" text NOT NULL,\\n\t\\\"source\\\" jsonb NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"gateway_thread_sessions\\\" (\\n\t\\\"thread_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"jobs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"target_id\\\" text NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"trigger\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"scheduled_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"attempt\\\" integer NOT NULL,\\n\t\\\"max_attempts\\\" integer NOT NULL,\\n\t\\\"leased_by\\\" text,\\n\t\\\"lease_expires_at\\\" timestamp with time zone,\\n\t\\\"completed_at\\\" timestamp with time zone,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"provider\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"token_strategy\\\" text NOT NULL,\\n\t\\\"client_id_ciphertext\\\" text NOT NULL,\\n\t\\\"client_secret_ciphertext\\\" text NOT NULL,\\n\t\\\"signing_secret_ciphertext\\\" text,\\n\t\\\"redirect_uri\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_connections\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"app_id\\\" text NOT NULL,\\n\t\\\"external_id\\\" text NOT NULL,\\n\t\\\"access_token_ciphertext\\\" text NOT NULL,\\n\t\\\"refresh_token_ciphertext\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"granted_scopes\\\" jsonb,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"connected_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"resource_activity\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"resource_kind\\\" text NOT NULL,\\n\t\\\"resource_id\\\" text NOT NULL,\\n\t\\\"last_opened_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"secret_values\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"ref_kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"field\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"skills\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trace_logs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"trace_id\\\" text NOT NULL,\\n\t\\\"span_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"level\\\" text NOT NULL,\\n\t\\\"message\\\" text NOT NULL,\\n\t\\\"data\\\" jsonb,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trace_spans\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"trace_id\\\" text NOT NULL,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"started_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_attachments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"target_kind\\\" text DEFAULT 'workflow' NOT NULL,\\n\t\\\"workflow_slug\\\" text,\\n\t\\\"agent_slug\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"source\\\" jsonb NOT NULL,\\n\t\\\"origin\\\" text DEFAULT 'project' NOT NULL,\\n\t\\\"prompt\\\" text,\\n\t\\\"lifecycle\\\" jsonb,\\n\t\\\"created_by_session_id\\\" text,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text NOT NULL,\\n\t\\\"source_path\\\" text,\\n\t\\\"trigger_type\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"triggered_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_schedules\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"attachment_slug\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"schedule\\\" text NOT NULL,\\n\t\\\"next_run_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"enabled\\\" integer NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"type\\\" text NOT NULL,\\n\t\\\"correlation_id\\\" text,\\n\t\\\"data\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_hooks\\\" (\\n\t\\\"hook_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"token\\\" text NOT NULL,\\n\t\\\"correlation_id\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"resumed_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"workflow_slug\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text,\\n\t\\\"subscription_id\\\" text,\\n\t\\\"trigger_run_id\\\" text,\\n\t\\\"parent_workflow_run_id\\\" text,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"trigger\\\" text NOT NULL,\\n\t\\\"triggered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"started_at\\\" timestamp with time zone,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"input\\\" jsonb,\\n\t\\\"output\\\" jsonb,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_subscriptions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"workflow_slug\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"enabled\\\" integer NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflows\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"subscribable\\\" integer NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD CONSTRAINT \\\"agent_events_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD CONSTRAINT \\\"agent_sessions_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_attachment_id_gateway_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"gateway_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_connections\\\" ADD CONSTRAINT \\\"oauth_connections_app_id_oauth_apps_id_fk\\\" FOREIGN KEY (\\\"app_id\\\") REFERENCES \\\"public\\\".\\\"oauth_apps\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_logs\\\" ADD CONSTRAINT \\\"trace_logs_span_id_trace_spans_id_fk\\\" FOREIGN KEY (\\\"span_id\\\") REFERENCES \\\"public\\\".\\\"trace_spans\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD CONSTRAINT \\\"trigger_runs_attachment_id_trigger_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"trigger_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_events\\\" ADD CONSTRAINT \\\"workflow_events_run_id_workflow_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"workflow_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_hooks\\\" ADD CONSTRAINT \\\"workflow_hooks_run_id_workflow_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"workflow_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_attachment_id_trigger_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"trigger_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_subscription_id_workflow_subscriptions_id_fk\\\" FOREIGN KEY (\\\"subscription_id\\\") REFERENCES \\\"public\\\".\\\"workflow_subscriptions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_trigger_run_id_trigger_runs_id_fk\\\" FOREIGN KEY (\\\"trigger_run_id\\\") REFERENCES \\\"public\\\".\\\"trigger_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_sessions_agent_updated_idx\\\" ON \\\"agent_sessions\\\" USING btree (\\\"agent_id\\\",\\\"updated_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"agents_project_id_slug_idx\\\" ON \\\"agents\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"agents_project_id_route_idx\\\" ON \\\"agents\\\" USING btree (\\\"project_id\\\",\\\"route\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_instances_project_slug_scope_label_unique\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"slug\\\",\\\"scope_type\\\",\\\"scope_id\\\",\\\"label\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_instances_project_slug_scope_idx\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"slug\\\",\\\"scope_type\\\",\\\"scope_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"gateway_attachments_project_id_slug_idx\\\" ON \\\"gateway_attachments\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"gateway_attachments_project_platform_channel_active\\\" ON \\\"gateway_attachments\\\" USING btree (\\\"project_id\\\",\\\"platform\\\",\\\"channel_id\\\") WHERE \\\"gateway_attachments\\\".\\\"deleted_at\\\" is null;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_apps_project_id_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_connections_app_external_unique\\\" ON \\\"oauth_connections\\\" USING btree (\\\"app_id\\\",\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"resource_activity_project_user_kind_resource\\\" ON \\\"resource_activity\\\" USING btree (\\\"project_id\\\",\\\"user_id\\\",\\\"resource_kind\\\",\\\"resource_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"resource_activity_user_last_opened_at\\\" ON \\\"resource_activity\\\" USING btree (\\\"user_id\\\",\\\"last_opened_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"secret_values_ref_unique\\\" ON \\\"secret_values\\\" USING btree (\\\"project_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\",\\\"field\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"secret_values_ref_idx\\\" ON \\\"secret_values\\\" USING btree (\\\"project_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"skills_project_id_slug_idx\\\" ON \\\"skills\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_logs_trace_id_seq_idx\\\" ON \\\"trace_logs\\\" USING btree (\\\"trace_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_logs_span_id_seq_idx\\\" ON \\\"trace_logs\\\" USING btree (\\\"span_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"trigger_attachments_project_id_slug_idx\\\" ON \\\"trigger_attachments\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"trigger_schedules_project_id_attachment_slug_idx\\\" ON \\\"trigger_schedules\\\" USING btree (\\\"project_id\\\",\\\"attachment_slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trigger_schedules_next_run_at_idx\\\" ON \\\"trigger_schedules\\\" USING btree (\\\"next_run_at\\\",\\\"enabled\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_events_run_id_seq_unique\\\" ON \\\"workflow_events\\\" USING btree (\\\"run_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_events_run_id_type_idx\\\" ON \\\"workflow_events\\\" USING btree (\\\"run_id\\\",\\\"type\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_events_correlation_id_idx\\\" ON \\\"workflow_events\\\" USING btree (\\\"correlation_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_hooks_token_unique\\\" ON \\\"workflow_hooks\\\" USING btree (\\\"token\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_hooks_run_id_idx\\\" ON \\\"workflow_hooks\\\" USING btree (\\\"run_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_runs_project_workflow_triggered_idx\\\" ON \\\"workflow_runs\\\" USING btree (\\\"project_id\\\",\\\"workflow_slug\\\",\\\"triggered_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_subscriptions_project_workflow_user\\\" ON \\\"workflow_subscriptions\\\" USING btree (\\\"project_id\\\",\\\"workflow_slug\\\",\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflows_project_id_slug_idx\\\" ON \\\"workflows\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781213647873,\n\t\t\"hash\": \"03d99ea3c47d7b7f9a3b73a9b767c82a29394e5b2c53868e55061bf0bed93e0b\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"ran_by_user_id\\\" text;\", \"\\nALTER TABLE \\\"workflow_runs\\\" ADD COLUMN \\\"ran_by_user_id\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781243850513,\n\t\t\"hash\": \"3f3eb52271a724ca488bfd6b2aba9095265455c55dee2a5d76d16c8698801906\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"canceled_at\\\" timestamp with time zone;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17813e8,\n\t\t\"hash\": \"3dbe010bde8652bd58886b33d5d8c449e7213ef66a6235c365598dc978802d71\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"agent_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"run_index\\\" integer NOT NULL,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"ran_by_user_id\\\" text,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"error\\\" jsonb,\\n\t\\\"started_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"total_cost_usd\\\" double precision,\\n\t\\\"total_tokens\\\" integer,\\n\t\\\"models_used\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"usage_records\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"run_kind\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"label\\\" text NOT NULL,\\n\t\\\"quantity\\\" integer,\\n\t\\\"unit\\\" text,\\n\t\\\"amount\\\" double precision NOT NULL,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD COLUMN \\\"run_id\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_runs\\\" ADD CONSTRAINT \\\"agent_runs_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_runs\\\" ADD CONSTRAINT \\\"agent_runs_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_session_run_index_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"session_id\\\",\\\"run_index\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_agent_started_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"agent_id\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_project_started_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"project_id\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"usage_records_run_run_kind_idx\\\" ON \\\"usage_records\\\" USING btree (\\\"run_id\\\",\\\"run_kind\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"usage_records_kind_idx\\\" ON \\\"usage_records\\\" USING btree (\\\"kind\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD CONSTRAINT \\\"agent_events_run_id_agent_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"agent_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781568153484,\n\t\t\"hash\": \"e40c228590351e229ed0fb39e8e3045e2b68368363675b2f147a694c6437a80e\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE IF EXISTS \\\"agent_runs\\\" DISABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nDROP TABLE IF EXISTS \\\"agent_runs\\\" CASCADE;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD COLUMN IF NOT EXISTS \\\"total_duration_ms\\\" integer DEFAULT 0 NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" DROP COLUMN IF EXISTS \\\"run_id\\\";\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781630388181,\n\t\t\"hash\": \"b995f6f4e5f1147c20ea90cd26877d7154ff1b1625adba277507268c2a8c35f6\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"DROP TABLE \\\"oauth_apps\\\" CASCADE;\",\n\t\t\t\"\\nDROP TABLE \\\"oauth_connections\\\" CASCADE;\",\n\t\t\t\"\\nDROP TABLE \\\"secret_values\\\" CASCADE;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781941661795,\n\t\t\"hash\": \"3816998a2a2c7ead79cacfb64281fd415220473dee9512192b05b8cb57516f74\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"shared_connection_id\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782243320892,\n\t\t\"hash\": \"ec36b70bcd148a39ac4f55789348aee32315070e7d8b75aff61a9cee1d245721\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"title\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"live_message\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"agents\\\" ADD COLUMN \\\"credential_keys\\\" jsonb;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782280074442,\n\t\t\"hash\": \"6174d3625965c6921bc20d51f67cc841b3e96b0d1c3777508a6969a2f2622f25\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"agents\\\" RENAME COLUMN \\\"credential_keys\\\" TO \\\"app_slugs\\\";\",\n\t\t\t\"\\nCREATE TABLE \\\"credential_assignments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"target_type\\\" text NOT NULL,\\n\t\\\"target_key\\\" text NOT NULL,\\n\t\\\"consumer_id\\\" text NOT NULL,\\n\t\\\"credential_slug\\\" text NOT NULL,\\n\t\\\"instance_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_assignments_project_target_consumer_slug\\\" ON \\\"credential_assignments\\\" USING btree (\\\"project_id\\\",\\\"target_type\\\",\\\"target_key\\\",\\\"consumer_id\\\",\\\"credential_slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_assignments_project_target_idx\\\" ON \\\"credential_assignments\\\" USING btree (\\\"project_id\\\",\\\"target_type\\\",\\\"target_key\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" RENAME COLUMN \\\"slug\\\" TO \\\"app_slug\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"slug\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"name\\\" text;\",\n\t\t\t\"\\nUPDATE \\\"credential_instances\\\" SET \\\"name\\\" = \\\"label\\\";\",\n\t\t\t\"\\nUPDATE \\\"credential_instances\\\" SET \\\"slug\\\" = CASE WHEN \\\"is_default\\\" = 1 THEN \\\"app_slug\\\" ELSE \\\"app_slug\\\" || '-' || substr(\\\"id\\\", 1, 8) END;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ALTER COLUMN \\\"slug\\\" SET NOT NULL;\",\n\t\t\t\"\\nDROP INDEX \\\"credential_instances_project_slug_scope_label_unique\\\";\",\n\t\t\t\"\\nDROP INDEX \\\"credential_instances_project_slug_scope_idx\\\";\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_instances_project_app_slug_scope_idx\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"app_slug\\\",\\\"scope_type\\\",\\\"scope_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_instances_project_scope_slug_unique\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"scope_type\\\",\\\"scope_id\\\",\\\"slug\\\");\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17826e8,\n\t\t\"hash\": \"ee310c8ce64fdc1b17cff8f138fee267eb1b1676262e58dae6e4c7e505295b4a\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"trigger_attachments\\\" ADD COLUMN \\\"name\\\" text;\", \"\\nALTER TABLE \\\"trigger_attachments\\\" ADD COLUMN \\\"description\\\" text;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17827e8,\n\t\t\"hash\": \"5ce9dbb84f2eaae456389abaca578d65e148ade609bf7f4e3debe55041163dd6\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"granted_scopes\\\" jsonb;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17828e8,\n\t\t\"hash\": \"643bd06059078751d2c1d03c61a21f56313a8feb89cf69ed97a8fb6fac66ea19\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"last_used_at\\\" timestamp with time zone;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17829e8,\n\t\t\"hash\": \"eb8a691e801cb24a2e6a41a1472bd61c838b6ecea23341dff7fa5d48414a9b05\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"triggers\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"origin\\\" text DEFAULT 'project' NOT NULL,\\n\t\\\"config\\\" jsonb,\\n\t\\\"schedule\\\" text,\\n\t\\\"next_run_at\\\" timestamp with time zone,\\n\t\\\"enabled\\\" integer DEFAULT 1 NOT NULL,\\n\t\\\"lifecycle\\\" jsonb,\\n\t\\\"created_by_session_id\\\" text,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"triggers_project_id_slug_idx\\\" ON \\\"triggers\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"triggers_next_run_at_enabled_idx\\\" ON \\\"triggers\\\" USING btree (\\\"next_run_at\\\",\\\"enabled\\\");\",\n\t\t\t\"\\nINSERT INTO \\\"triggers\\\" (\\n\t\\\"id\\\",\\n\t\\\"project_id\\\",\\n\t\\\"slug\\\",\\n\t\\\"kind\\\",\\n\t\\\"name\\\",\\n\t\\\"description\\\",\\n\t\\\"module_file\\\",\\n\t\\\"origin\\\",\\n\t\\\"config\\\",\\n\t\\\"schedule\\\",\\n\t\\\"next_run_at\\\",\\n\t\\\"enabled\\\",\\n\t\\\"lifecycle\\\",\\n\t\\\"created_by_session_id\\\",\\n\t\\\"registered_at\\\",\\n\t\\\"updated_at\\\",\\n\t\\\"deleted_at\\\"\\n)\\nSELECT\\n\tgen_random_uuid()::text,\\n\tg.project_id,\\n\tg.slug,\\n\tg.kind,\\n\tg.name,\\n\tg.description,\\n\tg.module_file,\\n\tg.origin,\\n\tg.config,\\n\tg.schedule,\\n\tg.next_run_at,\\n\tg.enabled,\\n\tg.lifecycle,\\n\tg.created_by_session_id,\\n\tg.registered_at,\\n\tg.updated_at,\\n\tg.deleted_at\\nFROM (\\n\tSELECT DISTINCT ON (ta.project_id, g.group_key)\\n\t\tta.project_id,\\n\t\tCASE\\n\t\t\tWHEN ta.origin = 'ephemeral' THEN ta.slug\\n\t\t\tELSE COALESCE(NULLIF(ta.source->>'slug', ''), NULLIF(ta.source->>'key', ''))\\n\t\tEND AS slug,\\n\t\t(ta.source->>'kind') AS kind,\\n\t\tta.name,\\n\t\tta.description,\\n\t\tta.module_file,\\n\t\tta.origin,\\n\t\tCASE\\n\t\t\tWHEN ta.source->>'kind' = 'webhook' THEN jsonb_strip_nulls(\\n\t\t\t\tjsonb_build_object(\\n\t\t\t\t\t'endpoint', ta.source->>'endpoint',\\n\t\t\t\t\t'requestSchema', ta.source->'requestSchema',\\n\t\t\t\t\t'filterSchema', ta.source->'filterSchema'\\n\t\t\t\t)\\n\t\t\t)\\n\t\t\tWHEN ta.source->>'kind' = 'poll' THEN jsonb_strip_nulls(\\n\t\t\t\tjsonb_build_object('code', ta.source->>'code', 'id', ta.source->>'id')\\n\t\t\t)\\n\t\t\tELSE NULL\\n\t\tEND AS config,\\n\t\tCASE\\n\t\t\tWHEN ta.source->>'kind' IN ('cron', 'poll') THEN ta.source->>'schedule'\\n\t\t\tELSE NULL\\n\t\tEND AS schedule,\\n\t\ts.next_run_at,\\n\t\tCOALESCE(s.enabled, 1) AS enabled,\\n\t\tta.lifecycle,\\n\t\tta.created_by_session_id,\\n\t\tta.registered_at,\\n\t\tta.updated_at,\\n\t\tta.deleted_at,\\n\t\tg.group_key\\n\tFROM trigger_attachments ta\\n\tINNER JOIN (\\n\t\tSELECT\\n\t\t\tid,\\n\t\t\tCASE\\n\t\t\t\tWHEN origin = 'ephemeral' THEN id\\n\t\t\t\tWHEN source->>'kind' = 'poll' AND source->>'id' IS NOT NULL THEN 'poll:' || (source->>'id')\\n\t\t\t\tELSE (source->>'kind') || ':' || COALESCE(NULLIF(source->>'slug', ''), NULLIF(source->>'key', ''))\\n\t\t\tEND AS group_key\\n\t\tFROM trigger_attachments\\n\t) g ON g.id = ta.id\\n\tLEFT JOIN LATERAL (\\n\t\tSELECT ts.next_run_at, ts.enabled\\n\t\tFROM trigger_schedules ts\\n\t\tWHERE ts.project_id = ta.project_id AND ts.attachment_slug = ta.slug\\n\t\tORDER BY ts.enabled DESC, ts.next_run_at ASC NULLS LAST\\n\t\tLIMIT 1\\n\t) s ON true\\n\tORDER BY ta.project_id, g.group_key, ta.registered_at ASC\\n) g;\\n\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ADD COLUMN \\\"trigger_id\\\" text;\",\n\t\t\t\"\\nUPDATE trigger_attachments ta\\nSET trigger_id = t.id\\nFROM triggers t\\nWHERE t.project_id = ta.project_id\\n\tAND t.kind = (ta.source->>'kind')\\n\tAND (\\n\t\t(ta.origin = 'ephemeral' AND t.origin = 'ephemeral' AND t.slug = ta.slug)\\n\t\tOR (\\n\t\t\tta.origin <> 'ephemeral'\\n\t\t\tAND t.origin = 'project'\\n\t\t\tAND t.slug = COALESCE(NULLIF(ta.source->>'slug', ''), NULLIF(ta.source->>'key', ''))\\n\t\t)\\n\t);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN IF NOT EXISTS \\\"outcome\\\" text DEFAULT 'dispatched' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN IF NOT EXISTS \\\"reason\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN IF NOT EXISTS \\\"detail\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN \\\"trigger_id\\\" text;\",\n\t\t\t\"\\nUPDATE trigger_runs tr\\nSET trigger_id = ta.trigger_id\\nFROM trigger_attachments ta\\nWHERE tr.attachment_id = ta.id;\\n\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" DROP CONSTRAINT \\\"trigger_runs_attachment_id_trigger_attachments_id_fk\\\";\",\n\t\t\t\"\\nDROP INDEX IF EXISTS \\\"trigger_runs_project_attachment_triggered_idx\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" DROP COLUMN \\\"attachment_id\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ALTER COLUMN \\\"trigger_id\\\" SET NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD CONSTRAINT \\\"trigger_runs_trigger_id_triggers_id_fk\\\" FOREIGN KEY (\\\"trigger_id\\\") REFERENCES \\\"public\\\".\\\"triggers\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"trigger_runs_project_trigger_triggered_idx\\\" ON \\\"trigger_runs\\\" USING btree (\\\"project_id\\\",\\\"trigger_id\\\",\\\"triggered_at\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"name\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"description\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"module_file\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"source\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"origin\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"lifecycle\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"created_by_session_id\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ALTER COLUMN \\\"trigger_id\\\" SET NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ADD CONSTRAINT \\\"trigger_attachments_trigger_id_triggers_id_fk\\\" FOREIGN KEY (\\\"trigger_id\\\") REFERENCES \\\"public\\\".\\\"triggers\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nDROP TABLE \\\"trigger_schedules\\\";\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1783e9,\n\t\t\"hash\": \"1413969c71976435768a9ade921f6da3e6e974a3b1c1dbaf9644536bd47f6507\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"trigger_hash\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_markdown\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_hash\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_model\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_status\\\" text DEFAULT 'idle' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_generated_at\\\" timestamp with time zone;\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17831e8,\n\t\t\"hash\": \"6bfdc822c7dffa912d818b7c46dfed152e15b0baa37c8117da0dd1f2123a8613\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"trigger_attachments\\\" ADD COLUMN \\\"disabled_at\\\" timestamp with time zone;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17832e8,\n\t\t\"hash\": \"c9bc827a4ca2fdb7326eb974e50aa185f1cb5db59921925a1baf9c9e544c8f4a\"\n\t},\n\t{\n\t\t\"sql\": [\"DROP INDEX \\\"credential_assignments_project_target_idx\\\";\", \"\\nCREATE INDEX \\\"agent_events_session_event_seq_idx\\\" ON \\\"agent_events\\\" USING btree (\\\"session_id\\\",\\\"event_type\\\",\\\"seq\\\");\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17833e8,\n\t\t\"hash\": \"be25c33ca471d79a0e536ed39c7e7b76183688398bd87edb200741290651fd1e\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"workflow_hooks\\\" ADD COLUMN \\\"schema\\\" jsonb;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17834e8,\n\t\t\"hash\": \"e10f62340d5a270245d9e3ed3c86c8158b95e7e254978e5b51c07c523a713788\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"workflows\\\" ALTER COLUMN \\\"name\\\" SET NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ALTER COLUMN \\\"description\\\" SET NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"run_input_values\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"canvas_annotations_json\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"canvas_annotations_hash\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"canvas_annotations_model\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"canvas_annotations_status\\\" text DEFAULT 'idle' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"canvas_annotations_generated_at\\\" timestamp with time zone;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"overview_summary\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"overview_phases_json\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"overview_hash\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"overview_model\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"overview_status\\\" text DEFAULT 'idle' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD COLUMN \\\"overview_generated_at\\\" timestamp with time zone;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1783400000001,\n\t\t\"hash\": \"2aa0640e57ab9e4e633c9734cd2987bf500a86b48611e60e0116e3966d8a9fb1\"\n\t}\n];\n//#endregion\n//#region src/migrate/run.ts\nasync function runMigrations(handle, migrationsFolder) {\n\tif (handle.dialect === \"postgres\") {\n\t\tconst config = {\n\t\t\tmigrationsFolder,\n\t\t\tmigrationsSchema: resolveMigrationsSchema(handle.searchPath)\n\t\t};\n\t\tconst loaded = loadMigrations(migrationsFolder, pgMigrations);\n\t\tconst migrations = handle.searchPath ? adaptPgMigrationsForSearchPath(loaded) : loaded;\n\t\tawait migratePgDatabase(handle.db, config, migrations);\n\t\treturn;\n\t}\n\tmigrate(handle.db, { migrationsFolder });\n}\n//#endregion\n//#region src/client/init.ts\nfunction resolveUrl(url) {\n\tif (url) return url;\n\tconst envUrl = process.env.DATABASE_URL?.trim();\n\tif (envUrl && inferDialect(envUrl) === \"sqlite\") return envUrl;\n\treturn resolveProjectDatabaseUrlFromEnv(process.env) ?? \"file:./data/dev.db\";\n}\nasync function initDatabase(options = {}) {\n\tif (isDatabaseInitialized()) return;\n\tconst url = resolveUrl(options.url);\n\tconst dialect = inferDialect(url, options.dialect);\n\tconst searchPath = resolveSearchPath(url, options.searchPath);\n\tconst next = createConnection({\n\t\turl,\n\t\tdialect,\n\t\tmax: options.max,\n\t\tsearchPath\n\t});\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n}\n//#endregion\n//#region src/client/project-database.ts\n/** Bind a Postgres handle for the org's shared runtime schema (all projects in the org). */\nasync function runWithProjectDatabase(options, fn) {\n\tconst poolOptions = {\n\t\turl: options.url,\n\t\tsearchPath: options.searchPath,\n\t\tmax: options.max,\n\t\trole: options.role\n\t};\n\tconst handle = await acquireProjectDatabasePool(poolOptions);\n\tconst closeOnRelease = inferDialect(options.url) !== \"postgres\";\n\treturn runWithRequestDatabaseHandle(handle, async () => {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\tif (closeOnRelease) await handle.close();\n\t\t\telse releaseProjectDatabasePool(poolOptions);\n\t\t}\n\t});\n}\n//#endregion\n//#region src/connection/pg/public-scoped-pool.ts\nconst PUBLIC_SEARCH_PATH = \"public\";\nfunction queryText(args) {\n\tconst first = args[0];\n\tif (typeof first === \"string\") return first;\n\treturn first.text;\n}\nfunction normalizeSqlCommand(text) {\n\treturn text?.trim().split(/\\s+/)[0]?.toUpperCase();\n}\nfunction isFullRollback(text) {\n\treturn text?.trim().toUpperCase() === \"ROLLBACK\";\n}\nasync function applyPublicScopePrologue(query) {\n\tawait query(`SET LOCAL search_path TO ${PUBLIC_SEARCH_PATH}`);\n}\nfunction bindQuery(originalQuery) {\n\treturn (...args) => Promise.resolve(originalQuery(...args));\n}\nfunction createPublicScopedClient(client) {\n\tconst originalQuery = bindQuery(client.query.bind(client));\n\tlet prologueApplied = false;\n\tclient.query = ((...args) => {\n\t\tconst sql = queryText(args);\n\t\tconst command = normalizeSqlCommand(sql);\n\t\tif (command === \"BEGIN\") return originalQuery(...args).then(async (result) => {\n\t\t\tif (!prologueApplied) {\n\t\t\t\tawait applyPublicScopePrologue(originalQuery);\n\t\t\t\tprologueApplied = true;\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t\tif (command === \"COMMIT\") {\n\t\t\tprologueApplied = false;\n\t\t\treturn originalQuery(...args);\n\t\t}\n\t\tif (command === \"ROLLBACK\" && isFullRollback(sql)) {\n\t\t\tprologueApplied = false;\n\t\t\treturn originalQuery(...args);\n\t\t}\n\t\tif (command === \"ROLLBACK\") return originalQuery(...args);\n\t\treturn originalQuery(...args);\n\t});\n\treturn client;\n}\nfunction createPublicScopedPool(pool) {\n\tconst scopedPool = Object.create(pool);\n\tscopedPool.query = (async (...args) => {\n\t\tconst client = await pool.connect();\n\t\tconst query = bindQuery(client.query.bind(client));\n\t\ttry {\n\t\t\tawait query(\"BEGIN\");\n\t\t\tawait applyPublicScopePrologue(query);\n\t\t\tconst result = await query(...args);\n\t\t\tawait query(\"COMMIT\");\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tawait query(\"ROLLBACK\").catch(() => void 0);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclient.release();\n\t\t}\n\t});\n\tscopedPool.connect = ((callback) => {\n\t\tif (callback) return pool.connect((error, client, release) => {\n\t\t\tif (error || !client) {\n\t\t\t\tcallback(error ?? /* @__PURE__ */ new Error(\"failed to connect\"), client, release);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcallback(null, createPublicScopedClient(client), release);\n\t\t});\n\t\treturn pool.connect().then((client) => createPublicScopedClient(client));\n\t});\n\treturn scopedPool;\n}\nfunction createPublicScopedHandle(options) {\n\tconst scopedPool = createPublicScopedPool(options.pool);\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(scopedPool),\n\t\tpool: scopedPool,\n\t\tsearchPath: PUBLIC_SEARCH_PATH,\n\t\tclose: async () => void 0\n\t};\n}\n//#endregion\n//#region src/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb() {\n\treturn getDbFromContext();\n}\n//#endregion\n//#region src/queries/agents/list-active.ts\n/**\n* List every active agent in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveAgents(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(agents.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(agents.projectId, options.projectIds));\n\treturn db.select().from(agents).where(and$1(...conditions)).orderBy(desc(agents.updatedAt));\n}\n//#endregion\n//#region src/queries/_internal/project-scope.ts\nfunction eqProjectScope(table) {\n\treturn eq$1(table.projectId, getProjectScopeId());\n}\nfunction scopedAnd(table, ...conditions) {\n\treturn and$1(eqProjectScope(table), ...conditions);\n}\nfunction projectScopeId() {\n\treturn getProjectScopeId();\n}\n/** Use with left joins on workflowRuns/triggerRuns/agentSessions keyed by trace or ref id. */\nfunction traceRootProjectScopeFilter() {\n\treturn or(eq$1(workflowRuns.projectId, getProjectScopeId()), eq$1(triggerRuns.projectId, getProjectScopeId()), eq$1(agentSessions.projectId, getProjectScopeId()));\n}\n//#endregion\n//#region src/queries/agents/select.ts\nasync function selectAgentBySlug(slug) {\n\treturn (await getDb().select().from(agents).where(scopedAnd(agents, eq$1(agents.slug, slug))).limit(1))[0];\n}\nasync function selectActiveAgentByRoute(route) {\n\treturn (await getDb().select({\n\t\tid: agents.id,\n\t\tslug: agents.slug\n\t}).from(agents).where(scopedAnd(agents, eq$1(agents.route, route), isNull(agents.deletedAt))).limit(1))[0];\n}\n/** Fetch active agents by id from the bound org schema (all projects). */\nasync function selectActiveAgentsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(agents).where(and$1(inArray$1(agents.id, ids), isNull(agents.deletedAt)));\n}\n/** Fetch a single active agent by id from the bound org schema (all projects). */\nasync function selectActiveAgentById(id) {\n\treturn (await getDb().select().from(agents).where(and$1(eq$1(agents.id, id), isNull(agents.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/agents/resolve-project-id.ts\n/** The agent row is the source of truth for which project it belongs to. */\nasync function resolveAgentProjectId(agentId) {\n\tconst agent = await selectActiveAgentById(agentId);\n\tif (!agent) throw new Error(`Agent not found: ${agentId}`);\n\treturn agent.projectId;\n}\n//#endregion\n//#region src/queries/agents/write.ts\nasync function insertAgent(values) {\n\tawait getDb().insert(agents).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateAgentById(id, values) {\n\tawait getDb().update(agents).set(values).where(scopedAnd(agents, eq$1(agents.id, id)));\n}\nasync function softDeleteAllAgents(now) {\n\tawait getDb().update(agents).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(agents, isNull(agents.deletedAt)));\n}\nasync function softDeleteAgentsNotInSlugs(slugs, now) {\n\tawait getDb().update(agents).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(agents, isNull(agents.deletedAt), notInArray(agents.slug, slugs)));\n}\n//#endregion\n//#region src/agents/cursor.ts\nfunction encodeAgentSessionCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\tupdatedAt: cursor.updatedAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeAgentSessionCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.updatedAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst updatedAt = new Date(parsed.updatedAt);\n\t\tif (Number.isNaN(updatedAt.getTime())) return null;\n\t\treturn {\n\t\t\tupdatedAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/queries/agent-sessions/index.ts\nasync function insertAgentSession(values) {\n\tawait getDb().insert(agentSessions).values({\n\t\t...values,\n\t\tsourceKind: values.sourceKind ?? \"api\",\n\t\tsourceId: values.sourceId ?? null,\n\t\tranByUserId: values.ranByUserId ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function selectActiveAgentSession(sessionId) {\n\treturn (await getDb().select().from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0];\n}\nasync function selectAgentSessionById(sessionId) {\n\treturn selectActiveAgentSession(sessionId);\n}\nasync function listAgentSessionsBySourceIds(options) {\n\tif (options.sourceIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.sourceKind, options.sourceKind), inArray$1(agentSessions.sourceId, options.sourceIds), isNull(agentSessions.deletedAt)));\n\tconst bySourceId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.sourceId) {\n\t\tconst bucket = bySourceId.get(row.sourceId) ?? [];\n\t\tbucket.push(row);\n\t\tbySourceId.set(row.sourceId, bucket);\n\t}\n\treturn bySourceId;\n}\nasync function selectAgentSessionForAgent(agentSlug, sessionId) {\n\treturn (await getDb().select({ session: agentSessions }).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(eq$1(agents.slug, agentSlug), eq$1(agents.projectId, projectScopeId()), eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0]?.session;\n}\nasync function touchAgentSession(sessionId, updatedAt) {\n\tawait getDb().update(agentSessions).set({ updatedAt }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function updateAgentSessionTitle(sessionId, title) {\n\tawait getDb().update(agentSessions).set({ title }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function addAgentSessionDuration(sessionId, deltaMs) {\n\tif (deltaMs <= 0) return;\n\tawait getDb().update(agentSessions).set({ totalDurationMs: sql$1`${agentSessions.totalDurationMs} + ${deltaMs}` }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nfunction cursorBefore$2(cursor) {\n\treturn or(lt(agentSessions.updatedAt, cursor.updatedAt), and$1(eq$1(agentSessions.updatedAt, cursor.updatedAt), lt(agentSessions.id, cursor.id)));\n}\nasync function listAgentSessionRowsPaginated(options) {\n\tconst db = getDb();\n\tconst conditions = [\n\t\teq$1(agents.slug, options.agentSlug),\n\t\teq$1(agents.projectId, projectScopeId()),\n\t\tisNull(agentSessions.deletedAt)\n\t];\n\tif (options.source) conditions.push(eq$1(agentSessions.sourceKind, options.source));\n\tif (options.cursor) {\n\t\tconst decoded = decodeAgentSessionCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore$2(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst sessions = (await db.select({ session: agentSessions }).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(...conditions)).orderBy(desc(agentSessions.updatedAt), desc(agentSessions.id)).limit(limit)).map((row) => row.session);\n\tconst hasMore = sessions.length > options.limit;\n\tconst page = hasMore ? sessions.slice(0, options.limit) : sessions;\n\tconst last = page.at(-1);\n\treturn {\n\t\trows: page,\n\t\tnextCursor: hasMore && last ? encodeAgentSessionCursor({\n\t\t\tupdatedAt: last.updatedAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\nasync function cancelAgentSessionRow(sessionId, canceledAt) {\n\treturn (await getDb().update(agentSessions).set({\n\t\tcanceledAt,\n\t\tupdatedAt: canceledAt\n\t}).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt), isNull(agentSessions.canceledAt))).returning())[0];\n}\n/**\n* Reactivates a session for a new run by clearing a prior cancellation. Cancellation\n* is per-run: a session is a multi-turn conversation, so a new prompt must not be blocked\n* (or perpetually shown as \"canceled\") just because an earlier turn was canceled. No-ops\n* when the session was not canceled.\n*/\nasync function clearAgentSessionCancellation(sessionId) {\n\tawait getDb().update(agentSessions).set({ canceledAt: null }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt), isNotNull(agentSessions.canceledAt)));\n}\nasync function updateSessionLiveMessage(sessionId, message) {\n\tawait getDb().update(agentSessions).set({ liveMessage: message }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function clearSessionLiveMessage(sessionId) {\n\tawait getDb().update(agentSessions).set({ liveMessage: null }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function selectSessionLiveMessage(sessionId) {\n\treturn (await getDb().select({ liveMessage: agentSessions.liveMessage }).from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0]?.liveMessage;\n}\n//#endregion\n//#region src/queries/agent-events/index.ts\nasync function maxSeqForSession(sessionId) {\n\treturn (await getDb().select({ value: max$1(agentEvents.seq) }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), isNull(agentEvents.deletedAt))))[0]?.value ?? 0;\n}\nasync function insertAgentEvent(values) {\n\tawait getDb().insert(agentEvents).values(values);\n}\nasync function listMessagePayloads(sessionId, messageEventType) {\n\treturn (await listMessageEventsForSession(sessionId, messageEventType)).map((row) => row.payload);\n}\nasync function listMessageEventsForSession(sessionId, messageEventType, options) {\n\tconst db = getDb();\n\tconst sinceSeq = options?.sinceSeq;\n\treturn await db.select({\n\t\tpayload: agentEvents.payload,\n\t\tcreatedAt: agentEvents.createdAt,\n\t\tseq: agentEvents.seq\n\t}).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt), sinceSeq != null && sinceSeq > 0 ? gt(agentEvents.seq, sinceSeq) : void 0)).orderBy(asc(agentEvents.seq));\n}\nasync function countMessageEventsForSession(sessionId, messageEventType) {\n\tconst rows = await getDb().select({ count: sql$1`count(*)` }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt)));\n\treturn Number(rows[0]?.count ?? 0);\n}\nasync function listAgentEventsForSession(sessionId) {\n\treturn (await getDb().select({ event: agentEvents }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), isNull(agentEvents.deletedAt))).orderBy(asc(agentEvents.seq))).map((row) => row.event);\n}\n//#endregion\n//#region src/queries/usage-records/index.ts\nasync function insertUsageRecord(values) {\n\tawait getDb().insert(usageRecords).values({\n\t\t...values,\n\t\tquantity: values.quantity ?? null,\n\t\tunit: values.unit ?? null,\n\t\tmetadata: values.metadata ?? null\n\t});\n}\nasync function listUsageRecordsForRun(runId, runKind) {\n\treturn getDb().select().from(usageRecords).where(and$1(eq$1(usageRecords.runId, runId), eq$1(usageRecords.runKind, runKind))).orderBy(asc(usageRecords.createdAt), asc(usageRecords.id));\n}\nasync function listUsageRecordsForRuns(runIds, runKind) {\n\tif (runIds.length === 0) return [];\n\treturn getDb().select().from(usageRecords).where(and$1(inArray$1(usageRecords.runId, runIds), eq$1(usageRecords.runKind, runKind))).orderBy(asc(usageRecords.createdAt), asc(usageRecords.id));\n}\n//#endregion\n//#region src/queries/triggers/index.ts\nasync function selectTriggerBySlug(slug) {\n\treturn (await getDb().select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.slug, slug))).limit(1))[0];\n}\nasync function selectTriggerById(id) {\n\treturn (await getDb().select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.id, id))).limit(1))[0];\n}\nasync function insertTrigger(values) {\n\tawait getDb().insert(triggers).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\torigin: values.origin ?? \"project\",\n\t\tenabled: values.enabled ?? 1\n\t});\n}\nasync function updateTriggerById(id, values) {\n\tawait getDb().update(triggers).set(values).where(scopedAnd(triggers, eq$1(triggers.id, id)));\n}\nasync function setTriggerOverviewGenerating(id, hash, now = /* @__PURE__ */ new Date()) {\n\tawait getDb().update(triggers).set({\n\t\toverviewStatus: \"generating\",\n\t\toverviewHash: hash,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.id, id)));\n}\nasync function updateTriggerOverview(id, values, now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst set = {\n\t\toverviewStatus: values.status,\n\t\tupdatedAt: now\n\t};\n\tif (values.markdown !== void 0) {\n\t\tset.overviewMarkdown = values.markdown;\n\t\tset.overviewGeneratedAt = now;\n\t}\n\tif (values.hash !== void 0) set.overviewHash = values.hash;\n\tif (values.model !== void 0) set.overviewModel = values.model;\n\tawait db.update(triggers).set(set).where(scopedAnd(triggers, eq$1(triggers.id, id)));\n}\nasync function softDeleteAllProjectTriggers(now) {\n\tawait getDb().update(triggers).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")));\n}\nasync function softDeleteProjectTriggersNotInSlugs(slugs, now) {\n\tawait getDb().update(triggers).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\"), notInArray(triggers.slug, slugs)));\n}\nasync function listActiveTriggersByProjectIds(projectIds) {\n\tconst db = getDb();\n\tif (projectIds !== void 0 && projectIds.length === 0) return [];\n\tconst conditions = [isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")];\n\tif (projectIds !== void 0) conditions.push(inArray$1(triggers.projectId, projectIds));\n\treturn db.select().from(triggers).where(and$1(...conditions));\n}\nasync function listActiveEphemeralTriggers() {\n\treturn getDb().select().from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\")));\n}\nasync function selectWebhookTriggers() {\n\treturn (await getDb().select().from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt)))).filter((row) => row.kind === \"webhook\");\n}\nasync function setTriggerScheduleEnabled(triggerSlug, enabled, now) {\n\tawait getDb().update(triggers).set({\n\t\tenabled: enabled ? 1 : 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.slug, triggerSlug)));\n}\nasync function disableAllTriggerSchedules(now) {\n\tawait getDb().update(triggers).set({\n\t\tenabled: 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"])));\n}\nasync function disableTriggerSchedulesNotInSlugs(triggerSlugs, now) {\n\tawait getDb().update(triggers).set({\n\t\tenabled: 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), notInArray(triggers.slug, triggerSlugs)));\n}\nasync function listEnabledScheduledTriggers() {\n\treturn getDb().select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt))).orderBy(asc(triggers.slug));\n}\nasync function claimDueTriggers(now, resolveNextRunAt, limit = 10) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst due = await tx.select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\t\tconst claimed = [];\n\t\tfor (const row of due) {\n\t\t\tif (!row.schedule) continue;\n\t\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\t\tconst [updated] = await tx.update(triggers).set({\n\t\t\t\tnextRunAt,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(scopedAnd(triggers, eq$1(triggers.id, row.id), lte(triggers.nextRunAt, now))).returning();\n\t\t\tif (updated) claimed.push(updated);\n\t\t}\n\t\treturn claimed;\n\t});\n\tconst due = await db.select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\tconst claimed = [];\n\tfor (const row of due) {\n\t\tif (!row.schedule) continue;\n\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\tawait db.update(triggers).set({\n\t\t\tnextRunAt,\n\t\t\tupdatedAt: now\n\t\t}).where(scopedAnd(triggers, eq$1(triggers.id, row.id), lte(triggers.nextRunAt, now)));\n\t\tconst updated = await selectTriggerById(row.id);\n\t\tif (updated && updated.nextRunAt?.getTime() === nextRunAt.getTime()) claimed.push(updated);\n\t}\n\treturn claimed;\n}\nasync function claimDueTriggersForOrg(now, resolveNextRunAt, limit = 10) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst due = await tx.select().from(triggers).where(and$1(eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\t\tconst claimed = [];\n\t\tfor (const row of due) {\n\t\t\tif (!row.schedule) continue;\n\t\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\t\tconst [updated] = await tx.update(triggers).set({\n\t\t\t\tnextRunAt,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(and$1(eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId), lte(triggers.nextRunAt, now))).returning();\n\t\t\tif (updated) claimed.push(updated);\n\t\t}\n\t\treturn claimed;\n\t});\n\tconst due = await db.select().from(triggers).where(and$1(eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\tconst claimed = [];\n\tfor (const row of due) {\n\t\tif (!row.schedule) continue;\n\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\tawait db.update(triggers).set({\n\t\t\tnextRunAt,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId), lte(triggers.nextRunAt, now)));\n\t\tconst trigger = (await db.select().from(triggers).where(and$1(eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId))).limit(1))[0];\n\t\tif (trigger && trigger.nextRunAt?.getTime() === nextRunAt.getTime()) claimed.push(trigger);\n\t}\n\treturn claimed;\n}\nasync function upsertTriggerScheduleFields(options) {\n\tawait getDb().update(triggers).set({\n\t\tschedule: options.schedule,\n\t\tnextRunAt: options.nextRunAt,\n\t\tenabled: options.enabled ? 1 : 0,\n\t\tupdatedAt: options.updatedAt\n\t}).where(scopedAnd(triggers, eq$1(triggers.slug, options.triggerSlug)));\n}\nasync function listTriggersByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(triggers).where(scopedAnd(triggers, inArray$1(triggers.id, ids)));\n}\n//#endregion\n//#region src/queries/trigger-attachments/helpers.ts\n/** Non-deleted and not user-disabled — eligible for trigger execution. */\nfunction isTriggerAttachmentExecutable(row) {\n\treturn row.deletedAt === null && row.disabledAt === null;\n}\nfunction triggerAttachmentStatusFromRow(row) {\n\tif (row.deletedAt !== null || row.disabledAt !== null) return \"disabled\";\n\treturn \"active\";\n}\n//#endregion\n//#region src/queries/trigger-attachments/index.ts\nasync function selectTriggerAttachmentBySlug(slug) {\n\treturn (await getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.slug, slug))).limit(1))[0];\n}\nasync function selectTriggerAttachmentById(id) {\n\treturn (await getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.id, id))).limit(1))[0];\n}\nasync function insertTriggerAttachment(values) {\n\tawait getDb().insert(triggerAttachments).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateTriggerAttachmentById(id, values) {\n\tawait getDb().update(triggerAttachments).set(values).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.id, id)));\n}\nasync function setTriggerAttachmentEnabled(id, enabled, now = /* @__PURE__ */ new Date()) {\n\tawait updateTriggerAttachmentById(id, {\n\t\tdisabledAt: enabled ? null : now,\n\t\tupdatedAt: now\n\t});\n}\nasync function softDeleteAllTriggerAttachments(now) {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\tconst ids = (await db.select({ id: triggers.id }).from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")))).map((row) => row.id);\n\tif (ids.length === 0) return;\n\tawait db.update(triggerAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), inArray$1(triggerAttachments.triggerId, ids)));\n}\nasync function softDeleteTriggerAttachmentsNotInSlugs(slugs, now) {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\tconst projectTriggerIds = (await db.select({ id: triggers.id }).from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")))).map((row) => row.id);\n\tif (projectTriggerIds.length === 0) return;\n\tawait db.update(triggerAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), notInArray(triggerAttachments.slug, slugs), inArray$1(triggerAttachments.triggerId, projectTriggerIds)));\n}\nasync function getTriggerAttachmentBySlug(slug) {\n\treturn selectTriggerAttachmentBySlug(slug);\n}\nasync function listActiveTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn (await db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")))).map((row) => row.attachment);\n}\nasync function listAttachmentsByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return [];\n\treturn getDb().select().from(triggerAttachments).where(and$1(isNull(triggerAttachments.deletedAt), inArray$1(triggerAttachments.triggerId, triggerIds)));\n}\n/** Non-deleted attachments that are not user-disabled — for trigger execution. */\nasync function listExecutableAttachmentsByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return [];\n\treturn getDb().select().from(triggerAttachments).where(and$1(isNull(triggerAttachments.deletedAt), isNull(triggerAttachments.disabledAt), inArray$1(triggerAttachments.triggerId, triggerIds)));\n}\nasync function selectEphemeralTriggerAttachmentsByAgentSlug(agentSlug) {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\"), eq$1(triggerAttachments.agentSlug, agentSlug))).then((rows) => rows.map((row) => row.attachment));\n}\nasync function selectTriggerAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.agentSlug, agentSlug)));\n}\nasync function selectEphemeralTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\"))).then((rows) => rows.map((row) => row.attachment));\n}\n/** Slugs of non-deleted attachments that are user-disabled. */\nasync function selectDisabledAttachmentSlugs(slugs) {\n\tif (slugs.length === 0) return /* @__PURE__ */ new Set();\n\tconst rows = await getDb().select({ slug: triggerAttachments.slug }).from(triggerAttachments).where(scopedAnd(triggerAttachments, inArray$1(triggerAttachments.slug, slugs), isNull(triggerAttachments.deletedAt), isNotNull(triggerAttachments.disabledAt)));\n\treturn new Set(rows.map((row) => row.slug));\n}\n/** @deprecated Use selectWebhookTriggers + listAttachmentsByTriggerIds */\nasync function selectWebhookTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.kind, \"webhook\"))).then((rows) => rows.map((row) => row.attachment));\n}\n//#endregion\n//#region src/workflows/cursor.ts\nfunction encodeWorkflowRunCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\ttriggeredAt: cursor.triggeredAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeWorkflowRunCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.triggeredAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst triggeredAt = new Date(parsed.triggeredAt);\n\t\tif (Number.isNaN(triggeredAt.getTime())) return null;\n\t\treturn {\n\t\t\ttriggeredAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/workflows/serialize.ts\nfunction toIso(value) {\n\tif (!value) return null;\n\treturn value.toISOString();\n}\nfunction workflowRunSummaryFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tstartedAt: toIso(row.startedAt),\n\t\tfinishedAt: toIso(row.finishedAt),\n\t\ttriggerRunId: row.triggerRunId ?? null,\n\t\tattachmentId: row.attachmentId ?? null,\n\t\tsourceKind: row.sourceKind,\n\t\tsourceId: row.sourceId ?? null\n\t};\n}\nfunction workflowRunRecordFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tworkflowSlug: row.workflowSlug,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tstartedAt: toIso(row.startedAt),\n\t\tfinishedAt: toIso(row.finishedAt),\n\t\tsourceKind: row.sourceKind,\n\t\tsourceId: row.sourceId ?? null,\n\t\ttriggerRunId: row.triggerRunId ?? null,\n\t\tattachmentId: row.attachmentId ?? null,\n\t\tparentWorkflowRunId: row.parentWorkflowRunId ?? null,\n\t\tparentSpanId: row.parentSpanId ?? null,\n\t\tinput: row.input ?? null,\n\t\toutput: row.output ?? null,\n\t\terror: row.error ?? null\n\t};\n}\nfunction triggerRunDetailFromRow(row, attachmentSlug) {\n\treturn {\n\t\tid: row.id,\n\t\ttriggerId: row.triggerId,\n\t\tattachmentSlug,\n\t\ttriggerType: row.triggerType,\n\t\tsourcePath: row.sourcePath ?? null,\n\t\tpayload: row.payload ?? null,\n\t\ttriggeredAt: row.triggeredAt.toISOString()\n\t};\n}\nfunction workflowStepRunFromEvent(row) {\n\treturn {\n\t\tid: row.id,\n\t\tactionKey: row.correlationId ?? row.id,\n\t\toutput: row.data ?? null,\n\t\tcompletedAt: row.createdAt.toISOString()\n\t};\n}\nfunction traceSpanToJson(span) {\n\treturn {\n\t\t...span,\n\t\tstartedAt: span.startedAt.toISOString(),\n\t\tfinishedAt: toIso(span.finishedAt)\n\t};\n}\nfunction traceLogToJson(log) {\n\treturn {\n\t\t...log,\n\t\tcreatedAt: log.createdAt.toISOString()\n\t};\n}\nfunction traceResponseToJson(trace) {\n\treturn {\n\t\ttraceId: trace.traceId,\n\t\ttrigger: trace.trigger,\n\t\tgateway: trace.gateway,\n\t\tspans: trace.spans.map(traceSpanToJson),\n\t\tlogs: trace.logs.map(traceLogToJson)\n\t};\n}\n//#endregion\n//#region src/queries/workflow-runs/index.ts\nasync function insertWorkflowRun(values) {\n\tawait getDb().insert(workflowRuns).values({\n\t\t...values,\n\t\tsourceKind: values.sourceKind ?? \"api\",\n\t\tsourceId: values.sourceId ?? null,\n\t\tranByUserId: values.ranByUserId ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function markWorkflowRunRunningRow(id, startedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"running\",\n\t\tstartedAt,\n\t\terror: null,\n\t\tfinishedAt: null\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id)));\n}\nasync function setWorkflowRunStatusRow(id, status) {\n\tawait getDb().update(workflowRuns).set({ status }).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id)));\n}\nasync function selectWorkflowRunById(id) {\n\treturn (await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id))).limit(1))[0];\n}\n/** Resolve the owning project for a run id across the whole org schema. */\nasync function resolveWorkflowRunProjectId(runId) {\n\tconst rows = await getDb().select({ projectId: workflowRuns.projectId }).from(workflowRuns).where(eq$1(workflowRuns.id, runId)).limit(1);\n\tif (!rows[0]) throw new Error(`Workflow run not found: ${runId}`);\n\treturn rows[0].projectId;\n}\nasync function completeWorkflowRunRow(id, output, finishedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"completed\",\n\t\toutput,\n\t\tfinishedAt,\n\t\terror: null\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), ne(workflowRuns.status, \"canceled\")));\n}\nasync function failWorkflowRunRow(id, error, finishedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"failed\",\n\t\terror,\n\t\tfinishedAt\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), ne(workflowRuns.status, \"canceled\")));\n}\nconst CANCELABLE_WORKFLOW_STATUSES = [\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\"\n];\nasync function cancelWorkflowRunRow(id, finishedAt) {\n\treturn (await getDb().update(workflowRuns).set({\n\t\tstatus: \"canceled\",\n\t\tfinishedAt\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), inArray$1(workflowRuns.status, CANCELABLE_WORKFLOW_STATUSES))).returning())[0];\n}\nasync function listWorkflowRunsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.workflowSlug, workflowSlug)));\n}\nasync function listWorkflowRunsByTriggerRunId(triggerRunId) {\n\treturn getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.triggerRunId, triggerRunId)));\n}\nasync function listWorkflowRunsByTriggerRunIds(triggerRunIds) {\n\tif (triggerRunIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, inArray$1(workflowRuns.triggerRunId, triggerRunIds)));\n\tconst byTriggerRunId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.triggerRunId) {\n\t\tconst bucket = byTriggerRunId.get(row.triggerRunId) ?? [];\n\t\tbucket.push(row);\n\t\tbyTriggerRunId.set(row.triggerRunId, bucket);\n\t}\n\treturn byTriggerRunId;\n}\nasync function selectWorkflowRunForWorkflow(workflowSlug, runId) {\n\treturn (await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, runId), eq$1(workflowRuns.workflowSlug, workflowSlug))).limit(1))[0];\n}\nfunction cursorBefore$1(cursor) {\n\treturn or(lt(workflowRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(workflowRuns.triggeredAt, cursor.triggeredAt), lt(workflowRuns.id, cursor.id)));\n}\nasync function listWorkflowRunsPaginated(options) {\n\tconst db = getDb();\n\tconst conditions = [eq$1(workflowRuns.workflowSlug, options.workflowSlug)];\n\tif (options.status) conditions.push(eq$1(workflowRuns.status, options.status));\n\tif (options.trigger) conditions.push(eq$1(workflowRuns.trigger, options.trigger));\n\tif (options.cursor) {\n\t\tconst decoded = decodeWorkflowRunCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore$1(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst rows = await db.select().from(workflowRuns).where(scopedAnd(workflowRuns, ...conditions)).orderBy(desc(workflowRuns.triggeredAt), desc(workflowRuns.id)).limit(limit);\n\tconst hasMore = rows.length > options.limit;\n\tconst page = hasMore ? rows.slice(0, options.limit) : rows;\n\tconst last = page.at(-1);\n\treturn {\n\t\titems: page.map(workflowRunSummaryFromRow),\n\t\tnextCursor: hasMore && last ? encodeWorkflowRunCursor({\n\t\t\ttriggeredAt: last.triggeredAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\n//#endregion\n//#region src/queries/workflow-events/index.ts\nasync function selectMaxEventSeq(runId) {\n\tconst rows = await getDb().select({ value: max$1(workflowEvents.seq) }).from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId)));\n\treturn Number(rows[0]?.value ?? -1);\n}\n/**\n* Append one event. Allocates the next per-run `seq` (max+1) and is idempotent\n* when an explicit `id` is supplied. Returns true when a row was inserted.\n*/\nasync function appendWorkflowEvent(values) {\n\tconst db = getDb();\n\tconst id = values.id ?? crypto.randomUUID();\n\tconst seq = await selectMaxEventSeq(values.runId) + 1;\n\treturn (await db.insert(workflowEvents).values({\n\t\tid,\n\t\trunId: values.runId,\n\t\tprojectId: projectScopeId(),\n\t\tseq,\n\t\ttype: values.type,\n\t\tcorrelationId: values.correlationId ?? null,\n\t\tdata: values.data ?? null,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t}).onConflictDoNothing({ target: workflowEvents.id }).returning({ id: workflowEvents.id })).length > 0;\n}\nasync function listReplayEvents(runId) {\n\treturn getDb().select().from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId))).orderBy(asc(workflowEvents.seq));\n}\n/** Completed step events for a run, in execution order — backs the run-detail steps view. */\nasync function listStepCompletedEvents(runId) {\n\treturn getDb().select().from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId), eq$1(workflowEvents.type, \"step_completed\"))).orderBy(asc(workflowEvents.seq));\n}\n//#endregion\n//#region src/queries/workflow-hooks/index.ts\n/** Idempotent on `token` so replays don't create duplicate hook rows. */\nasync function insertWorkflowHook(values) {\n\tawait getDb().insert(workflowHooks).values({\n\t\thookId: values.hookId,\n\t\trunId: values.runId,\n\t\tprojectId: projectScopeId(),\n\t\ttoken: values.token,\n\t\tcorrelationId: values.correlationId,\n\t\tstatus: \"waiting\",\n\t\tschema: values.schema ?? null,\n\t\tpayload: values.payload ?? null,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tresumedAt: null\n\t}).onConflictDoNothing({ target: workflowHooks.token });\n}\n/** Hooks for a run (newest-creation last), optionally filtered by status. */\nasync function listWorkflowHooksByRun(runId, options) {\n\tconst db = getDb();\n\tconst conditions = [eq$1(workflowHooks.runId, runId)];\n\tif (options?.status) conditions.push(eq$1(workflowHooks.status, options.status));\n\treturn db.select().from(workflowHooks).where(scopedAnd(workflowHooks, ...conditions)).orderBy(asc(workflowHooks.createdAt));\n}\nasync function selectWorkflowHookByToken(token) {\n\treturn (await getDb().select().from(workflowHooks).where(scopedAnd(workflowHooks, eq$1(workflowHooks.token, token))).limit(1))[0];\n}\nasync function markWorkflowHookResumed(hookId, payload) {\n\tawait getDb().update(workflowHooks).set({\n\t\tstatus: \"resumed\",\n\t\tpayload,\n\t\tresumedAt: /* @__PURE__ */ new Date()\n\t}).where(scopedAnd(workflowHooks, eq$1(workflowHooks.hookId, hookId)));\n}\n//#endregion\n//#region src/triggers/cursor.ts\nfunction encodeTriggerRunCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\ttriggeredAt: cursor.triggeredAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeTriggerRunCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.triggeredAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst triggeredAt = new Date(parsed.triggeredAt);\n\t\tif (Number.isNaN(triggeredAt.getTime())) return null;\n\t\treturn {\n\t\t\ttriggeredAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/triggers/serialize.ts\nfunction triggerRunSummaryFromRow(row, options) {\n\treturn {\n\t\tid: row.id,\n\t\ttriggerType: row.triggerType,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tsourcePath: row.sourcePath ?? null,\n\t\toutcome: row.outcome,\n\t\treason: row.reason ?? null,\n\t\tdetail: row.detail ?? null,\n\t\tworkflowRuns: (options?.workflowRuns ?? []).map((workflowRun) => ({\n\t\t\tid: workflowRun.id,\n\t\t\tstatus: workflowRun.status,\n\t\t\tworkflowSlug: workflowRun.workflowSlug\n\t\t})),\n\t\tagentSessions: (options?.agentSessions ?? []).map((session) => ({\n\t\t\tid: session.id,\n\t\t\tagentSlug: session.agentSlug\n\t\t}))\n\t};\n}\nfunction triggerRunRecordFromRow(row, attachmentSlug, triggerId = row.triggerId) {\n\treturn {\n\t\tid: row.id,\n\t\ttriggerId,\n\t\tattachmentSlug,\n\t\ttriggerType: row.triggerType,\n\t\tsourcePath: row.sourcePath ?? null,\n\t\toutcome: row.outcome,\n\t\treason: row.reason ?? null,\n\t\tdetail: row.detail ?? null,\n\t\tpayload: row.payload ?? null,\n\t\ttriggeredAt: row.triggeredAt.toISOString()\n\t};\n}\n//#endregion\n//#region src/queries/trigger-runs/index.ts\nasync function insertTriggerRun(values) {\n\tawait getDb().insert(triggerRuns).values({\n\t\t...values,\n\t\toutcome: values.outcome ?? \"dispatched\",\n\t\treason: values.reason ?? null,\n\t\tdetail: values.detail ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function selectTriggerRunById(id) {\n\treturn (await getDb().select().from(triggerRuns).where(scopedAnd(triggerRuns, eq$1(triggerRuns.id, id))).limit(1))[0];\n}\nasync function selectTriggerRunForTrigger(triggerId, runId) {\n\treturn (await getDb().select().from(triggerRuns).where(scopedAnd(triggerRuns, eq$1(triggerRuns.id, runId), eq$1(triggerRuns.triggerId, triggerId))).limit(1))[0];\n}\nfunction cursorBefore(cursor) {\n\treturn or(lt(triggerRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(triggerRuns.triggeredAt, cursor.triggeredAt), lt(triggerRuns.id, cursor.id)));\n}\nasync function listTriggerRunRowsPaginated(options) {\n\tif (options.triggerIds.length === 0) return {\n\t\titems: [],\n\t\tnextCursor: null\n\t};\n\tconst db = getDb();\n\tconst conditions = [inArray$1(triggerRuns.triggerId, options.triggerIds)];\n\tif (options.triggerType) conditions.push(eq$1(triggerRuns.triggerType, options.triggerType));\n\tif (options.cursor) {\n\t\tconst decoded = decodeTriggerRunCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst rows = await db.select().from(triggerRuns).where(scopedAnd(triggerRuns, ...conditions)).orderBy(desc(triggerRuns.triggeredAt), desc(triggerRuns.id)).limit(limit);\n\tconst hasMore = rows.length > options.limit;\n\tconst page = hasMore ? rows.slice(0, options.limit) : rows;\n\tconst last = page.at(-1);\n\tconst workflowRunsByTriggerRunId = await listWorkflowRunsByTriggerRunIds(page.map((row) => row.id));\n\treturn {\n\t\titems: page.map((row) => triggerRunSummaryFromRow(row, { workflowRuns: workflowRunsByTriggerRunId.get(row.id) ?? [] })),\n\t\tnextCursor: hasMore && last ? encodeTriggerRunCursor({\n\t\t\ttriggeredAt: last.triggeredAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\nasync function selectTriggerLastFiredAtByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\ttriggerId: triggerRuns.triggerId,\n\t\tlastFiredAt: max$1(triggerRuns.triggeredAt)\n\t}).from(triggerRuns).where(inArray$1(triggerRuns.triggerId, triggerIds)).groupBy(triggerRuns.triggerId);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastFiredAt) result.set(row.triggerId, row.lastFiredAt);\n\treturn result;\n}\nasync function selectTriggerFireCountByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\ttriggerId: triggerRuns.triggerId,\n\t\tfireCount: count()\n\t}).from(triggerRuns).where(inArray$1(triggerRuns.triggerId, triggerIds)).groupBy(triggerRuns.triggerId);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) result.set(row.triggerId, Number(row.fireCount));\n\treturn result;\n}\n//#endregion\n//#region src/queries/jobs/index.ts\nconst DEFAULT_LEASE_MS = 300 * 1e3;\nasync function insertJob(values) {\n\tawait getDb().insert(jobs).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function claimPendingJob(workerId, leaseExpiresAt, now) {\n\tconst db = getDb();\n\tconst job = (await db.select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.status, \"pending\"), lte(jobs.scheduledAt, now))).orderBy(asc(jobs.scheduledAt)).limit(1))[0];\n\tif (!job) return;\n\tawait db.update(jobs).set({\n\t\tstatus: \"leased\",\n\t\tleasedBy: workerId,\n\t\tleaseExpiresAt\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, job.id), eq$1(jobs.status, \"pending\")));\n\tconst claimed = await selectJobById(job.id);\n\tif (claimed?.status !== \"leased\" || claimed.leasedBy !== workerId) return;\n\treturn claimed;\n}\nasync function claimNextJobRow(workerId, leaseMs = DEFAULT_LEASE_MS) {\n\tconst db = getDb();\n\tconst dialect = getDatabaseHandle().dialect;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst leaseExpiresAt = new Date(now.getTime() + leaseMs);\n\tif (dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst job = (await tx.select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.status, \"pending\"), lte(jobs.scheduledAt, now))).orderBy(asc(jobs.scheduledAt)).limit(1))[0];\n\t\tif (!job) return;\n\t\tawait tx.update(jobs).set({\n\t\t\tstatus: \"leased\",\n\t\t\tleasedBy: workerId,\n\t\t\tleaseExpiresAt\n\t\t}).where(scopedAnd(jobs, eq$1(jobs.id, job.id)));\n\t\treturn {\n\t\t\t...job,\n\t\t\tstatus: \"leased\",\n\t\t\tleasedBy: workerId,\n\t\t\tleaseExpiresAt\n\t\t};\n\t});\n\treturn claimPendingJob(workerId, leaseExpiresAt, now);\n}\nasync function markJobRunning(id) {\n\tawait getDb().update(jobs).set({ status: \"running\" }).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function completeJobRow(id, completedAt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"completed\",\n\t\tcompletedAt,\n\t\terror: null\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function failJobRow(id, error, completedAt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"failed\",\n\t\terror,\n\t\tcompletedAt\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function requeueExpiredLeases(now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst expired = await db.select({ id: jobs.id }).from(jobs).where(scopedAnd(jobs, inArray$1(jobs.status, [\"leased\", \"running\"]), isNotNull(jobs.leaseExpiresAt), lt(jobs.leaseExpiresAt, now)));\n\tif (expired.length === 0) return 0;\n\tawait db.update(jobs).set({\n\t\tstatus: \"pending\",\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null\n\t}).where(scopedAnd(jobs, inArray$1(jobs.id, expired.map((row) => row.id))));\n\treturn expired.length;\n}\nasync function selectJobById(id) {\n\treturn (await getDb().select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.id, id))).limit(1))[0];\n}\nasync function selectJobByRunId(runId) {\n\treturn (await getDb().select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.runId, runId))).limit(1))[0];\n}\nasync function resetJobForRetry(id, scheduledAt, attempt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"pending\",\n\t\tscheduledAt,\n\t\tattempt,\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null,\n\t\tcompletedAt: null,\n\t\terror: null\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\n//#endregion\n//#region src/queries/gateway-attachments/index.ts\nasync function selectGatewayAttachmentBySlug(slug) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.slug, slug))).limit(1))[0];\n}\nasync function selectGatewayAttachmentById(id) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, id))).limit(1))[0];\n}\n/** Thrown when a channel is already bound by a different project in the same organization. */\nvar GatewayChannelConflictError = class extends Error {\n\tplatform;\n\tchannelId;\n\townerProjectId;\n\tconstructor(platform, channelId, ownerProjectId) {\n\t\tsuper(`Channel ${channelId} is already bound to another project in this organization`);\n\t\tthis.platform = platform;\n\t\tthis.channelId = channelId;\n\t\tthis.ownerProjectId = ownerProjectId;\n\t\tthis.name = \"GatewayChannelConflictError\";\n\t}\n};\n/** Project-unscoped active binding for a channel — used to enforce org-unique channel ownership. */\nasync function getActiveOrgGatewayAttachmentByChannel(platform, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\n/** Project-unscoped binding for a Slack workspace channel. */\nasync function getActiveOrgGatewayAttachmentByTeamAndChannel(platform, teamId, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.teamId, teamId), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\nasync function getActiveGatewayAttachmentByChannel(platform, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\nasync function listActiveGatewayAttachments() {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, isNull(gatewayAttachments.deletedAt)));\n}\n/**\n* Project-unscoped: every active attachment for a platform across all projects in the current org\n* schema, joined to its agent's registry id. Used by the platform ingress, which routes by channel\n* before a project scope is known. A single query avoids per-attachment agent lookups.\n*/\nasync function listActiveOrgGatewayBindingsByPlatform(platform) {\n\treturn getDb().select({\n\t\tattachmentId: gatewayAttachments.id,\n\t\tslug: gatewayAttachments.slug,\n\t\tagentSlug: gatewayAttachments.agentSlug,\n\t\tagentId: agents.id,\n\t\tchannelId: gatewayAttachments.channelId,\n\t\tteamId: gatewayAttachments.teamId,\n\t\tsource: gatewayAttachments.source,\n\t\tprojectId: gatewayAttachments.projectId\n\t}).from(gatewayAttachments).innerJoin(agents, and$1(eq$1(agents.projectId, gatewayAttachments.projectId), eq$1(agents.slug, gatewayAttachments.agentSlug), isNull(agents.deletedAt))).where(and$1(eq$1(gatewayAttachments.platform, platform), isNull(gatewayAttachments.deletedAt)));\n}\nasync function listActiveGatewayAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.agentSlug, agentSlug), isNull(gatewayAttachments.deletedAt)));\n}\nasync function softDeleteGatewayAttachmentsForAgentPlatformTeam(agentSlug, platform, teamId, now) {\n\tconst db = getDb();\n\tconst targets = (await listActiveGatewayAttachmentsByAgentSlug(agentSlug)).filter((row) => row.platform === platform && (teamId === null ? row.teamId == null : row.teamId === teamId));\n\tif (targets.length === 0) return 0;\n\tfor (const row of targets) await db.update(gatewayAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, row.id)));\n\treturn targets.length;\n}\nasync function listActiveGatewayAttachmentsByPlatform(platform) {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.platform, platform), isNull(gatewayAttachments.deletedAt)));\n}\nasync function insertGatewayAttachment(values) {\n\tawait getDb().insert(gatewayAttachments).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateGatewayAttachmentById(id, values) {\n\tawait getDb().update(gatewayAttachments).set(values).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, id)));\n}\nasync function softDeleteGatewayAttachmentByChannel(platform, channelId, now) {\n\tconst existing = await getActiveGatewayAttachmentByChannel(platform, channelId);\n\tif (!existing) return false;\n\tawait getDb().update(gatewayAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, existing.id)));\n\treturn true;\n}\nasync function upsertGatewayAttachmentByChannel(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slug = gatewayAttachmentKeyForChannel(options.platform, options.channelId);\n\tconst existing = await getActiveGatewayAttachmentByChannel(options.platform, options.channelId);\n\tif (existing) {\n\t\tawait updateGatewayAttachmentById(existing.id, {\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tmoduleFile: \"\",\n\t\t\tplatform: options.platform,\n\t\t\tteamId: options.teamId ?? existing.teamId,\n\t\t\tchannelId: options.channelId,\n\t\t\tsource: options.source,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tconst updated = await selectGatewayAttachmentById(existing.id);\n\t\tif (!updated) throw new Error(\"Failed to load gateway attachment after update\");\n\t\treturn updated;\n\t}\n\tconst orgOwned = await getActiveOrgGatewayAttachmentByChannel(options.platform, options.channelId);\n\tif (orgOwned && orgOwned.projectId !== projectScopeId()) throw new GatewayChannelConflictError(options.platform, options.channelId, orgOwned.projectId);\n\tconst softDeleted = await selectGatewayAttachmentBySlug(slug);\n\tif (softDeleted && softDeleted.deletedAt) {\n\t\tawait updateGatewayAttachmentById(softDeleted.id, {\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tmoduleFile: \"\",\n\t\t\tplatform: options.platform,\n\t\t\tteamId: options.teamId ?? softDeleted.teamId,\n\t\t\tchannelId: options.channelId,\n\t\t\tsource: options.source,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tconst revived = await selectGatewayAttachmentById(softDeleted.id);\n\t\tif (!revived) throw new Error(\"Failed to load gateway attachment after revive\");\n\t\treturn revived;\n\t}\n\tconst id = crypto.randomUUID();\n\tawait insertGatewayAttachment({\n\t\tid,\n\t\tslug,\n\t\tagentSlug: options.agentSlug,\n\t\tmoduleFile: \"\",\n\t\tplatform: options.platform,\n\t\tteamId: options.teamId ?? null,\n\t\tchannelId: options.channelId,\n\t\tsource: options.source,\n\t\tregisteredAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\tconst inserted = await selectGatewayAttachmentById(id);\n\tif (!inserted) throw new Error(\"Failed to load gateway attachment after insert\");\n\treturn inserted;\n}\nasync function getGatewayAttachmentBySlug(slug) {\n\treturn selectGatewayAttachmentBySlug(slug);\n}\n//#endregion\n//#region src/queries/gateway-thread-sessions/index.ts\nasync function selectGatewayThreadSessionByThreadId(threadId) {\n\treturn (await getDb().select({ session: gatewayThreadSessions }).from(gatewayThreadSessions).innerJoin(gatewayAttachments, eq$1(gatewayAttachments.id, gatewayThreadSessions.attachmentId)).where(scopedAnd(gatewayAttachments, eq$1(gatewayThreadSessions.threadId, threadId))).limit(1))[0]?.session;\n}\nasync function selectGatewayThreadSessionBySessionId(sessionId) {\n\treturn (await getDb().select({ session: gatewayThreadSessions }).from(gatewayThreadSessions).innerJoin(gatewayAttachments, eq$1(gatewayAttachments.id, gatewayThreadSessions.attachmentId)).where(scopedAnd(gatewayAttachments, eq$1(gatewayThreadSessions.sessionId, sessionId))).limit(1))[0]?.session;\n}\nasync function upsertGatewayThreadSession(values) {\n\tawait getDb().insert(gatewayThreadSessions).values(values).onConflictDoUpdate({\n\t\ttarget: gatewayThreadSessions.threadId,\n\t\tset: {\n\t\t\tagentId: values.agentId,\n\t\t\tsessionId: values.sessionId,\n\t\t\tattachmentId: values.attachmentId,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}\n\t});\n}\n//#endregion\n//#region src/queries/workflows/list-active.ts\n/**\n* List every active workflow in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveWorkflows(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(workflows.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(workflows.projectId, options.projectIds));\n\treturn db.select().from(workflows).where(and$1(...conditions)).orderBy(desc(workflows.updatedAt));\n}\n//#endregion\n//#region src/queries/workflows/select.ts\nasync function selectWorkflowBySlug(slug) {\n\treturn (await getDb().select().from(workflows).where(scopedAnd(workflows, eq$1(workflows.slug, slug))).limit(1))[0];\n}\nasync function selectActiveWorkflowBySlug(slug) {\n\treturn (await getDb().select().from(workflows).where(scopedAnd(workflows, eq$1(workflows.slug, slug), isNull(workflows.deletedAt))).limit(1))[0];\n}\n/** Fetch active workflows by id from the bound org schema (all projects). */\nasync function selectActiveWorkflowsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(workflows).where(and$1(inArray$1(workflows.id, ids), isNull(workflows.deletedAt)));\n}\n/** Fetch a single active workflow by id from the bound org schema (all projects). */\nasync function selectActiveWorkflowById(id) {\n\treturn (await getDb().select().from(workflows).where(and$1(eq$1(workflows.id, id), isNull(workflows.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/workflows/write.ts\nasync function insertWorkflow(values) {\n\tawait getDb().insert(workflows).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\tsubscribable: values.subscribable ? 1 : 0\n\t});\n}\nasync function updateWorkflowById(id, values) {\n\tawait getDb().update(workflows).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tmoduleFile: values.moduleFile,\n\t\tsubscribable: values.subscribable ? 1 : 0,\n\t\tupdatedAt: values.updatedAt,\n\t\tdeletedAt: values.deletedAt\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, id)));\n}\nasync function softDeleteAllWorkflows(now) {\n\tawait getDb().update(workflows).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, isNull(workflows.deletedAt)));\n}\nasync function softDeleteWorkflowsNotInSlugs(slugs, now) {\n\tawait getDb().update(workflows).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, isNull(workflows.deletedAt), notInArray(workflows.slug, slugs)));\n}\n//#endregion\n//#region src/queries/workflows/run-inputs.ts\nasync function selectWorkflowRunInputValues(workflowId) {\n\treturn (await getDb().select({ runInputValues: workflows.runInputValues }).from(workflows).where(scopedAnd(workflows, eq$1(workflows.id, workflowId))).limit(1))[0]?.runInputValues ?? null;\n}\nasync function updateWorkflowRunInputValues(workflowId, values) {\n\tawait getDb().update(workflows).set({\n\t\trunInputValues: values,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\n//#endregion\n//#region src/queries/workflows/canvas-annotations.ts\nasync function selectWorkflowCanvasAnnotations(workflowId) {\n\tconst row = (await getDb().select({\n\t\tstatus: workflows.canvasAnnotationsStatus,\n\t\thash: workflows.canvasAnnotationsHash,\n\t\tmodel: workflows.canvasAnnotationsModel,\n\t\tannotations: workflows.canvasAnnotationsJson,\n\t\tgeneratedAt: workflows.canvasAnnotationsGeneratedAt\n\t}).from(workflows).where(scopedAnd(workflows, eq$1(workflows.id, workflowId))).limit(1))[0];\n\tif (!row) return;\n\treturn {\n\t\tstatus: row.status,\n\t\thash: row.hash ?? null,\n\t\tmodel: row.model ?? null,\n\t\tannotations: row.annotations ?? null,\n\t\tgeneratedAt: row.generatedAt ?? null\n\t};\n}\nasync function setWorkflowCanvasAnnotationsGenerating(workflowId, hash, now = /* @__PURE__ */ new Date()) {\n\tawait getDb().update(workflows).set({\n\t\tcanvasAnnotationsStatus: \"generating\",\n\t\tcanvasAnnotationsHash: hash,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\nasync function updateWorkflowCanvasAnnotations(workflowId, values, now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst set = {\n\t\tcanvasAnnotationsStatus: values.status,\n\t\tupdatedAt: now\n\t};\n\tif (values.annotations !== void 0) {\n\t\tset.canvasAnnotationsJson = values.annotations;\n\t\tset.canvasAnnotationsGeneratedAt = now;\n\t}\n\tif (values.hash !== void 0) set.canvasAnnotationsHash = values.hash;\n\tif (values.model !== void 0) set.canvasAnnotationsModel = values.model;\n\tawait db.update(workflows).set(set).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\n//#endregion\n//#region src/queries/workflows/overview.ts\nasync function selectWorkflowOverview(workflowId) {\n\tconst row = (await getDb().select({\n\t\tstatus: workflows.overviewStatus,\n\t\tsummary: workflows.overviewSummary,\n\t\tphases: workflows.overviewPhasesJson,\n\t\thash: workflows.overviewHash,\n\t\tmodel: workflows.overviewModel,\n\t\tgeneratedAt: workflows.overviewGeneratedAt\n\t}).from(workflows).where(scopedAnd(workflows, eq$1(workflows.id, workflowId))).limit(1))[0];\n\tif (!row) return;\n\treturn {\n\t\tstatus: row.status,\n\t\tsummary: row.summary ?? null,\n\t\tphases: row.phases ?? null,\n\t\thash: row.hash ?? null,\n\t\tmodel: row.model ?? null,\n\t\tgeneratedAt: row.generatedAt ?? null\n\t};\n}\nasync function setWorkflowOverviewGenerating(workflowId, hash, now = /* @__PURE__ */ new Date()) {\n\tawait getDb().update(workflows).set({\n\t\toverviewStatus: \"generating\",\n\t\toverviewHash: hash,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\nasync function updateWorkflowOverview(workflowId, values, now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst set = {\n\t\toverviewStatus: values.status,\n\t\tupdatedAt: now\n\t};\n\tif (values.summary !== void 0) {\n\t\tset.overviewSummary = values.summary;\n\t\tset.overviewGeneratedAt = now;\n\t}\n\tif (values.phases !== void 0) set.overviewPhasesJson = values.phases;\n\tif (values.hash !== void 0) set.overviewHash = values.hash;\n\tif (values.model !== void 0) set.overviewModel = values.model;\n\tawait db.update(workflows).set(set).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\n//#endregion\n//#region src/queries/skills/list-active.ts\n/**\n* List every active skill in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveSkills(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(skills.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(skills.projectId, options.projectIds));\n\treturn db.select().from(skills).where(and$1(...conditions)).orderBy(desc(skills.updatedAt));\n}\n//#endregion\n//#region src/queries/skills/select.ts\nasync function selectSkillBySlug(slug) {\n\treturn (await getDb().select().from(skills).where(scopedAnd(skills, eq$1(skills.slug, slug))).limit(1))[0];\n}\n/** Fetch active skills by id from the bound org schema (all projects). */\nasync function selectActiveSkillsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(skills).where(and$1(inArray$1(skills.id, ids), isNull(skills.deletedAt)));\n}\n/** Fetch a single active skill by id from the bound org schema (all projects). */\nasync function selectActiveSkillById(id) {\n\treturn (await getDb().select().from(skills).where(and$1(eq$1(skills.id, id), isNull(skills.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/skills/write.ts\nasync function insertSkill(values) {\n\tawait getDb().insert(skills).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateSkillById(id, values) {\n\tawait getDb().update(skills).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tmoduleFile: values.moduleFile,\n\t\tupdatedAt: values.updatedAt,\n\t\tdeletedAt: values.deletedAt\n\t}).where(scopedAnd(skills, eq$1(skills.id, id)));\n}\nasync function softDeleteAllSkills(now) {\n\tawait getDb().update(skills).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(skills, isNull(skills.deletedAt)));\n}\nasync function softDeleteSkillsNotInSlugs(slugs, now) {\n\tawait getDb().update(skills).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(skills, isNull(skills.deletedAt), notInArray(skills.slug, slugs)));\n}\n//#endregion\n//#region src/queries/workflow-subscriptions/index.ts\nasync function selectWorkflowSubscriptionById(id) {\n\treturn (await getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id))).limit(1))[0];\n}\nasync function selectWorkflowSubscriptionByWorkflowAndUser(workflowSlug, userId) {\n\treturn (await getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug), eq$1(workflowSubscriptions.userId, userId))).limit(1))[0];\n}\nasync function listWorkflowSubscriptionsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug)));\n}\nasync function listEnabledWorkflowSubscriptionsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug), eq$1(workflowSubscriptions.enabled, 1)));\n}\nasync function insertWorkflowSubscription(values) {\n\tawait getDb().insert(workflowSubscriptions).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\tenabled: values.enabled ? 1 : 0\n\t});\n}\nasync function updateWorkflowSubscriptionById(id, values) {\n\tawait getDb().update(workflowSubscriptions).set({\n\t\tenabled: values.enabled ? 1 : 0,\n\t\tupdatedAt: values.updatedAt\n\t}).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id)));\n}\nasync function deleteWorkflowSubscriptionById(id) {\n\tif (!await selectWorkflowSubscriptionById(id)) return false;\n\tawait getDb().delete(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id)));\n\treturn true;\n}\n//#endregion\n//#region src/queries/resource-activity/index.ts\nasync function selectResourceActivityByUserAndResource(input) {\n\treturn (await getDb().select().from(resourceActivity).where(and$1(eq$1(resourceActivity.projectId, input.projectId), eq$1(resourceActivity.userId, input.userId), eq$1(resourceActivity.resourceKind, input.resourceKind), eq$1(resourceActivity.resourceId, input.resourceId))).limit(1))[0];\n}\nasync function touchResourceActivity(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst existing = await selectResourceActivityByUserAndResource(input);\n\tconst db = getDb();\n\tif (existing) {\n\t\tawait db.update(resourceActivity).set({ lastOpenedAt: now }).where(eq$1(resourceActivity.id, existing.id));\n\t\treturn;\n\t}\n\tawait db.insert(resourceActivity).values({\n\t\tid: crypto.randomUUID(),\n\t\tprojectId: input.projectId,\n\t\tuserId: input.userId,\n\t\tresourceKind: input.resourceKind,\n\t\tresourceId: input.resourceId,\n\t\tlastOpenedAt: now\n\t});\n}\nasync function listRecentResourceActivity(userId, limit) {\n\treturn getDb().select().from(resourceActivity).where(eq$1(resourceActivity.userId, userId)).orderBy(desc(resourceActivity.lastOpenedAt)).limit(limit);\n}\n//#endregion\n//#region src/queries/resource-last-run/index.ts\n/**\n* Last run per workflow id from the bound org schema.\n*\n* Runs are keyed by (projectId, workflowSlug), so join onto the workflows\n* registry to resolve ids. Account pages span all projects in the org, so this\n* intentionally does not use the ALS project scope — the join already matches\n* each run to its own project's workflow row.\n*/\nasync function selectWorkflowLastRunAtByIds(workflowIds) {\n\tif (workflowIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tworkflowId: workflows.id,\n\t\tlastRunAt: max(workflowRuns.triggeredAt)\n\t}).from(workflowRuns).innerJoin(workflows, and(eq(workflows.projectId, workflowRuns.projectId), eq(workflows.slug, workflowRuns.workflowSlug))).where(inArray(workflows.id, workflowIds)).groupBy(workflows.id);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastRunAt) result.set(row.workflowId, row.lastRunAt);\n\treturn result;\n}\n/**\n* Last session activity per agent id from the bound org schema.\n*\n* Agent ids are unique within the org schema, so no project scope filter is\n* needed (and the ALS scope is not bound on account routes anyway).\n*/\nasync function selectAgentLastRunAtByIds(agentIds) {\n\tif (agentIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tagentId: agentSessions.agentId,\n\t\tlastRunAt: max(agentSessions.updatedAt)\n\t}).from(agentSessions).where(inArray(agentSessions.agentId, agentIds)).groupBy(agentSessions.agentId);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastRunAt) result.set(row.agentId, row.lastRunAt);\n\treturn result;\n}\n//#endregion\n//#region src/queries/project-metrics/select-resource-counts.ts\n/**\n* Active resource counts grouped by project id across the bound org schema. Not\n* project scoped — the org database schema is itself the tenant boundary.\n*/\nasync function selectProjectResourceCounts(options) {\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return {};\n\tconst db = getDb();\n\tconst projectIds = options?.projectIds;\n\tconst agentConditions = [isNull(agents.deletedAt)];\n\tconst workflowConditions = [isNull(workflows.deletedAt)];\n\tconst skillConditions = [isNull(skills.deletedAt)];\n\tconst credentialConditions = [eq$1(credentialInstances.scopeType, \"project\")];\n\tif (projectIds !== void 0) {\n\t\tagentConditions.push(inArray$1(agents.projectId, projectIds));\n\t\tworkflowConditions.push(inArray$1(workflows.projectId, projectIds));\n\t\tskillConditions.push(inArray$1(skills.projectId, projectIds));\n\t\tcredentialConditions.push(inArray$1(credentialInstances.projectId, projectIds));\n\t}\n\tconst [agentRows, workflowRows, skillRows, credentialRows] = await Promise.all([\n\t\tdb.select({\n\t\t\tprojectId: agents.projectId,\n\t\t\tcount: count()\n\t\t}).from(agents).where(and$1(...agentConditions)).groupBy(agents.projectId),\n\t\tdb.select({\n\t\t\tprojectId: workflows.projectId,\n\t\t\tcount: count()\n\t\t}).from(workflows).where(and$1(...workflowConditions)).groupBy(workflows.projectId),\n\t\tdb.select({\n\t\t\tprojectId: skills.projectId,\n\t\t\tcount: count()\n\t\t}).from(skills).where(and$1(...skillConditions)).groupBy(skills.projectId),\n\t\tdb.select({\n\t\t\tprojectId: credentialInstances.projectId,\n\t\t\tcount: count()\n\t\t}).from(credentialInstances).where(and$1(...credentialConditions)).groupBy(credentialInstances.projectId)\n\t]);\n\tconst metrics = {};\n\tconst ensure = (projectId) => {\n\t\tlet entry = metrics[projectId];\n\t\tif (!entry) {\n\t\t\tentry = {\n\t\t\t\tagentCount: 0,\n\t\t\t\tworkflowCount: 0,\n\t\t\t\tskillCount: 0,\n\t\t\t\tcredentialCount: 0\n\t\t\t};\n\t\t\tmetrics[projectId] = entry;\n\t\t}\n\t\treturn entry;\n\t};\n\tfor (const row of agentRows) ensure(row.projectId).agentCount = Number(row.count);\n\tfor (const row of workflowRows) ensure(row.projectId).workflowCount = Number(row.count);\n\tfor (const row of skillRows) ensure(row.projectId).skillCount = Number(row.count);\n\tfor (const row of credentialRows) ensure(row.projectId).credentialCount = Number(row.count);\n\treturn metrics;\n}\n//#endregion\n//#region src/agents/serialize.ts\nfunction agentSessionStatusFromSpan(span, messageCount, canceledAt) {\n\tif (canceledAt) return \"canceled\";\n\tif (span) {\n\t\tif (span.status === \"running\") return \"running\";\n\t\tif (span.status === \"error\") return \"failed\";\n\t\treturn \"completed\";\n\t}\n\treturn messageCount > 0 ? \"completed\" : \"running\";\n}\nfunction agentSessionSummaryFromParts(options) {\n\treturn {\n\t\tid: options.row.id,\n\t\tstatus: options.status,\n\t\tsource: options.row.sourceKind,\n\t\tsourceId: options.row.sourceId ?? null,\n\t\ttitle: options.row.title ?? null,\n\t\tranByUserName: options.ranByUserName ?? null,\n\t\tgatewayPlatform: options.gatewayPlatform ?? null,\n\t\ttriggerType: options.triggerType ?? null,\n\t\tcreatedAt: options.row.createdAt.toISOString(),\n\t\tupdatedAt: options.row.updatedAt.toISOString(),\n\t\tmessageCount: options.messageCount\n\t};\n}\nfunction agentSessionRecordFromParts(options) {\n\treturn {\n\t\tid: options.row.id,\n\t\tagentSlug: options.agentSlug,\n\t\tstatus: options.status,\n\t\tsource: options.row.sourceKind,\n\t\tsourceId: options.row.sourceId ?? null,\n\t\tcreatedAt: options.row.createdAt.toISOString(),\n\t\tupdatedAt: options.row.updatedAt.toISOString(),\n\t\tparentSpanId: options.row.parentSpanId ?? null,\n\t\tmessageCount: options.messageCount,\n\t\terror: options.error,\n\t\ttotalDurationMs: options.row.totalDurationMs\n\t};\n}\nfunction gatewaySessionDetailFromParts(gateway, attachmentSlug) {\n\treturn {\n\t\tthreadId: gateway.threadId,\n\t\tattachmentId: gateway.attachmentId,\n\t\tattachmentSlug\n\t};\n}\nfunction agentEventFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tsessionId: row.sessionId,\n\t\tseq: row.seq,\n\t\teventType: row.eventType,\n\t\tpayload: row.payload,\n\t\tcreatedAt: row.createdAt.toISOString()\n\t};\n}\nfunction sessionErrorFromSpan(span) {\n\tif (!span || span.status !== \"error\") return null;\n\treturn span.error ?? null;\n}\n//#endregion\n//#region src/agents/types.ts\nconst MESSAGE_EVENT_TYPE = \"message\";\n//#endregion\n//#region src/tracing/sink.ts\nconst FLUSH_INTERVAL_MS = 50;\nconst FLUSH_BATCH_SIZE = 100;\nfunction createDatabaseTracingSink() {\n\tconst pending = [];\n\tconst seqByTrace = /* @__PURE__ */ new Map();\n\tlet flushTimer;\n\tasync function flushNow() {\n\t\tif (flushTimer) {\n\t\t\tclearTimeout(flushTimer);\n\t\t\tflushTimer = void 0;\n\t\t}\n\t\tif (pending.length === 0) return;\n\t\tawait insertTraceLogs(pending.splice(0, pending.length));\n\t}\n\tfunction scheduleFlush() {\n\t\tif (flushTimer) return;\n\t\tflushTimer = setTimeout(() => {\n\t\t\tflushTimer = void 0;\n\t\t\tflushNow().catch((error) => {\n\t\t\t\tconsole.error(\"[tracing] failed to flush logs:\", error);\n\t\t\t});\n\t\t}, FLUSH_INTERVAL_MS);\n\t}\n\tasync function nextSeq(traceId) {\n\t\tconst cached = seqByTrace.get(traceId);\n\t\tif (cached !== void 0) {\n\t\t\tconst next = cached + 1;\n\t\t\tseqByTrace.set(traceId, next);\n\t\t\treturn next;\n\t\t}\n\t\tconst next = await maxTraceLogSeq(traceId) + 1;\n\t\tseqByTrace.set(traceId, next);\n\t\treturn next;\n\t}\n\treturn {\n\t\tasync openSpan(span) {\n\t\t\tawait insertTraceSpan({\n\t\t\t\tid: span.id,\n\t\t\t\ttraceId: span.traceId,\n\t\t\t\tparentSpanId: span.parentSpanId ?? null,\n\t\t\t\tkind: span.kind,\n\t\t\t\trefId: span.refId,\n\t\t\t\tname: span.name,\n\t\t\t\tstatus: \"running\",\n\t\t\t\tstartedAt: span.startedAt,\n\t\t\t\tmetadata: span.metadata ?? null\n\t\t\t});\n\t\t},\n\t\tasync closeSpan(spanId, status, finishedAt, error) {\n\t\t\tawait updateTraceSpanStatus(spanId, status, finishedAt, error);\n\t\t\tawait flushNow();\n\t\t},\n\t\tasync appendLog(entry) {\n\t\t\tconst seq = await nextSeq(entry.traceId);\n\t\t\tpending.push({\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\ttraceId: entry.traceId,\n\t\t\t\tspanId: entry.spanId,\n\t\t\t\tseq,\n\t\t\t\tlevel: entry.level,\n\t\t\t\tmessage: entry.message,\n\t\t\t\tdata: entry.data,\n\t\t\t\tsource: entry.source,\n\t\t\t\tcreatedAt: entry.createdAt\n\t\t\t});\n\t\t\tif (pending.length >= FLUSH_BATCH_SIZE) {\n\t\t\t\tawait flushNow();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tscheduleFlush();\n\t\t},\n\t\tflushNow\n\t};\n}\n//#endregion\n//#region src/tracing/index.ts\nfunction triggerFromSpans(spans) {\n\tconst triggerSpan = spans.find((span) => span.kind === \"trigger_run\");\n\tif (!triggerSpan?.metadata || typeof triggerSpan.metadata !== \"object\") return null;\n\tconst metadata = triggerSpan.metadata;\n\treturn {\n\t\ttriggerType: String(metadata.triggerType ?? \"unknown\"),\n\t\ttriggerRunId: triggerSpan.refId,\n\t\tworkflowSlug: typeof metadata.workflowSlug === \"string\" ? metadata.workflowSlug : void 0,\n\t\tagentSlug: typeof metadata.agentSlug === \"string\" ? metadata.agentSlug : void 0,\n\t\tattachmentId: typeof metadata.attachmentId === \"string\" ? metadata.attachmentId : null,\n\t\tattachmentSlug: typeof metadata.attachmentSlug === \"string\" ? metadata.attachmentSlug : null,\n\t\troute: typeof metadata.route === \"string\" ? metadata.route : void 0,\n\t\tsourcePath: typeof metadata.sourcePath === \"string\" ? metadata.sourcePath : null\n\t};\n}\nfunction gatewayFromSpans(spans) {\n\tconst gatewaySpan = spans.find((span) => span.kind === \"gateway_event\");\n\tif (!gatewaySpan?.metadata || typeof gatewaySpan.metadata !== \"object\") return null;\n\tconst metadata = gatewaySpan.metadata;\n\tif (typeof metadata.gatewayAttachmentId !== \"string\" || typeof metadata.gatewayAttachmentKey !== \"string\") return null;\n\treturn {\n\t\tgatewayAttachmentId: metadata.gatewayAttachmentId,\n\t\tgatewayAttachmentKey: metadata.gatewayAttachmentKey,\n\t\tthreadId: typeof metadata.threadId === \"string\" ? metadata.threadId : void 0,\n\t\tchannelId: typeof metadata.channelId === \"string\" ? metadata.channelId : void 0,\n\t\tmode: typeof metadata.mode === \"string\" ? metadata.mode : void 0\n\t};\n}\nasync function getTraceForWorkflowRun(workflowRunId) {\n\tconst run = await selectWorkflowRunById(workflowRunId);\n\tif (!run) return null;\n\tlet traceId = workflowRunId;\n\tif (run.triggerRunId) traceId = run.triggerRunId;\n\telse {\n\t\tconst workflowSpan = await selectTraceSpanByRefId(workflowRunId);\n\t\tif (workflowSpan) traceId = workflowSpan.traceId;\n\t}\n\tconst spans = await listTraceSpansByTraceId(traceId);\n\tconst logs = await listTraceLogsByTraceId(traceId);\n\treturn {\n\t\ttraceId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\nasync function getTraceForTriggerRun(triggerRunId) {\n\tconst spans = await listTraceSpansByTraceId(triggerRunId);\n\tif (spans.length === 0) return null;\n\tconst logs = await listTraceLogsByTraceId(triggerRunId);\n\treturn {\n\t\ttraceId: triggerRunId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\nasync function getTraceForAgentSession(sessionId) {\n\tconst traceId = (await selectTraceSpanByRefId(sessionId))?.traceId ?? sessionId;\n\tconst spans = await listTraceSpansByTraceId(traceId);\n\tconst logs = await listTraceLogsByTraceId(traceId);\n\tif (spans.length === 0 && logs.length === 0) return null;\n\treturn {\n\t\ttraceId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\n//#endregion\n//#region src/agents/session-api.ts\nasync function resolveGatewayPlatform(row) {\n\tif (row.sourceKind !== \"gateway\" || !row.sourceId) return null;\n\treturn (await selectGatewayAttachmentById(row.sourceId))?.platform ?? null;\n}\nasync function resolveTriggerType(row) {\n\tif (row.sourceKind !== \"trigger\" || !row.sourceId) return null;\n\treturn (await selectTriggerRunById(row.sourceId))?.triggerType ?? null;\n}\nasync function enrichSessionRow(row) {\n\tconst [span, gateway, messageCount] = await Promise.all([\n\t\tselectLatestAgentSessionSpanByRefId(row.id),\n\t\tselectGatewayThreadSessionBySessionId(row.id),\n\t\tcountMessageEventsForSession(row.id, MESSAGE_EVENT_TYPE)\n\t]);\n\treturn {\n\t\tspan,\n\t\tgateway,\n\t\tmessageCount,\n\t\tstatus: agentSessionStatusFromSpan(span, messageCount, row.canceledAt)\n\t};\n}\nasync function buildAgentSessionSummary(row, options) {\n\tconst enriched = await enrichSessionRow(row);\n\tconst [gatewayPlatform, triggerType, ranByUserName] = await Promise.all([\n\t\tresolveGatewayPlatform(row),\n\t\tresolveTriggerType(row),\n\t\trow.ranByUserId && options?.resolveUserName ? options.resolveUserName(row.ranByUserId) : Promise.resolve(null)\n\t]);\n\treturn agentSessionSummaryFromParts({\n\t\trow,\n\t\tstatus: enriched.status,\n\t\tmessageCount: enriched.messageCount,\n\t\tgatewayPlatform,\n\t\ttriggerType,\n\t\tranByUserName\n\t});\n}\nasync function listAgentSessionsPaginated(options) {\n\tconst items = [];\n\tlet cursor = options.cursor;\n\tlet nextCursor = null;\n\twhile (items.length < options.limit) {\n\t\tconst page = await listAgentSessionRowsPaginated({\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tlimit: options.limit,\n\t\t\tcursor,\n\t\t\tsource: options.source\n\t\t});\n\t\tfor (const row of page.rows) {\n\t\t\tconst summary = await buildAgentSessionSummary(row, { resolveUserName: options.resolveUserName });\n\t\t\tif (options.status && summary.status !== options.status) continue;\n\t\t\titems.push(summary);\n\t\t\tif (items.length >= options.limit) {\n\t\t\t\tnextCursor = page.nextCursor;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (items.length >= options.limit || !page.nextCursor) {\n\t\t\tif (items.length < options.limit) nextCursor = null;\n\t\t\tbreak;\n\t\t}\n\t\tcursor = page.nextCursor;\n\t}\n\treturn {\n\t\titems,\n\t\tnextCursor\n\t};\n}\nasync function buildAgentSessionDetail(options) {\n\tconst row = await selectAgentSessionForAgent(options.agentSlug, options.sessionId);\n\tif (!row) return null;\n\tconst enriched = await enrichSessionRow(row);\n\tconst includeGateway = options.include.includes(\"gateway\");\n\tconst includeMessages = options.include.includes(\"messages\");\n\tconst includeEvents = options.include.includes(\"events\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tlet gateway = null;\n\tif (includeGateway && enriched.gateway) {\n\t\tconst attachment = await selectGatewayAttachmentById(enriched.gateway.attachmentId);\n\t\tgateway = gatewaySessionDetailFromParts(enriched.gateway, attachment?.slug ?? null);\n\t}\n\tconst messages = includeMessages ? await listMessagePayloads(row.id, MESSAGE_EVENT_TYPE) : [];\n\tconst events = includeEvents ? (await listAgentEventsForSession(row.id)).map(agentEventFromRow) : [];\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForAgentSession(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\tsession: agentSessionRecordFromParts({\n\t\t\trow,\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tstatus: enriched.status,\n\t\t\tmessageCount: enriched.messageCount,\n\t\t\terror: sessionErrorFromSpan(enriched.span)\n\t\t}),\n\t\tgateway,\n\t\tmessages,\n\t\tevents,\n\t\ttrace\n\t};\n}\nfunction messagePayloadWithSentAt(payload, createdAt, seq) {\n\treturn {\n\t\t...typeof payload === \"object\" && payload !== null && !Array.isArray(payload) ? payload : { content: payload },\n\t\tsentAt: createdAt.toISOString(),\n\t\tseq\n\t};\n}\n/**\n* Returns the persisted chat state for a session. `messages` is the full\n* transcript by default, or only events with `seq > sinceSeq` when a cursor is\n* supplied — the chat UI polls with its highest seen seq so each poll ships only\n* new turns plus the (separate, transient) `live` streaming message. Each\n* message carries its `seq` so the client can advance the cursor and key the row.\n*/\nasync function buildAgentSessionChatState(sessionId, options) {\n\tconst row = await selectActiveAgentSession(sessionId);\n\tif (!row) return null;\n\tconst enriched = await enrichSessionRow(row);\n\tconst [messageEvents, live] = await Promise.all([listMessageEventsForSession(row.id, MESSAGE_EVENT_TYPE, { sinceSeq: options?.sinceSeq }), selectSessionLiveMessage(row.id)]);\n\tconst messages = messageEvents.map(({ payload, createdAt, seq }) => messagePayloadWithSentAt(payload, createdAt, seq));\n\treturn {\n\t\tstatus: enriched.status,\n\t\tmessages,\n\t\tlive: live ?? null\n\t};\n}\n//#endregion\n//#region src/workflows/run-detail.ts\nasync function buildWorkflowRunDetail(options) {\n\tconst row = await selectWorkflowRunForWorkflow(options.workflowSlug, options.runId);\n\tif (!row) return null;\n\tconst includeTrigger = options.include.includes(\"trigger\");\n\tconst includeSteps = options.include.includes(\"steps\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tlet trigger = null;\n\tif (includeTrigger && row.triggerRunId) {\n\t\tconst triggerRun = await selectTriggerRunById(row.triggerRunId);\n\t\tif (triggerRun) {\n\t\t\tlet attachmentSlug = null;\n\t\t\tif (row.attachmentId) attachmentSlug = (await selectTriggerAttachmentById(row.attachmentId))?.slug ?? null;\n\t\t\ttrigger = triggerRunDetailFromRow(triggerRun, attachmentSlug);\n\t\t}\n\t}\n\tconst steps = includeSteps ? (await listStepCompletedEvents(row.id)).map(workflowStepRunFromEvent) : [];\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForWorkflowRun(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\trun: workflowRunRecordFromRow(row),\n\t\ttrigger,\n\t\tsteps,\n\t\ttrace\n\t};\n}\n//#endregion\n//#region src/history/helpers.ts\nfunction titleCaseResourceName(slug, explicitName) {\n\tif (explicitName?.trim()) return explicitName.trim();\n\tconst normalized = slug.split(/[/_-]+/).filter(Boolean).join(\" \");\n\tif (!normalized) return slug;\n\treturn normalized.replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\nfunction triggerLabelFromRaw(raw) {\n\tif (raw === \"api\") return \"API\";\n\treturn raw.charAt(0).toUpperCase() + raw.slice(1);\n}\nfunction timeInQueueMsBetween(triggeredAt, startedAt) {\n\tif (!startedAt) return null;\n\treturn Math.max(0, startedAt.getTime() - triggeredAt.getTime());\n}\nfunction buildHistoryUsage(records, durationMs) {\n\tconst grouped = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst key = `${record.kind}:${record.label}`;\n\t\tconst existing = grouped.get(key);\n\t\tif (existing) existing.amountUsd += record.amountUsd;\n\t\telse grouped.set(key, {\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amountUsd\n\t\t});\n\t}\n\tconst lineItems = [...grouped.entries()].map(([id, item]) => ({\n\t\tid,\n\t\tlabel: item.label,\n\t\tamountUsd: item.amountUsd\n\t}));\n\treturn {\n\t\trunDurationMs: durationMs,\n\t\tlineItems,\n\t\ttotalExcludingDurationUsd: lineItems.reduce((sum, item) => sum + item.amountUsd, 0)\n\t};\n}\n//#endregion\n//#region src/history/trace-messages.ts\nfunction metadataRecord(metadata) {\n\tif (metadata && typeof metadata === \"object\" && !Array.isArray(metadata)) return metadata;\n\treturn {};\n}\nfunction attachMessagesToAgentSessionSpans(spans, messages) {\n\tconst sessionSpans = spans.filter((span) => span.kind === \"agent_session\").sort((left, right) => Date.parse(left.startedAt) - Date.parse(right.startedAt));\n\tif (sessionSpans.length === 0) return spans;\n\tconst sortedMessages = [...messages].sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime());\n\tconst messagesBySpanId = /* @__PURE__ */ new Map();\n\tfor (let index = 0; index < sessionSpans.length; index += 1) {\n\t\tconst span = sessionSpans[index];\n\t\tconst windowStartMs = Date.parse(span.startedAt);\n\t\tconst windowEndMs = index + 1 < sessionSpans.length ? Date.parse(sessionSpans[index + 1].startedAt) : Number.POSITIVE_INFINITY;\n\t\tconst slice = sortedMessages.filter((message) => {\n\t\t\tconst createdAtMs = message.createdAt.getTime();\n\t\t\treturn createdAtMs >= windowStartMs && createdAtMs < windowEndMs;\n\t\t}).map((message) => message.payload);\n\t\tmessagesBySpanId.set(span.id, slice);\n\t}\n\treturn spans.map((span) => {\n\t\tif (span.kind !== \"agent_session\") return span;\n\t\tconst { messages: _stale, ...rest } = metadataRecord(span.metadata);\n\t\treturn {\n\t\t\t...span,\n\t\t\tmetadata: {\n\t\t\t\t...rest,\n\t\t\t\tmessages: messagesBySpanId.get(span.id) ?? []\n\t\t\t}\n\t\t};\n\t});\n}\n//#endregion\n//#region src/history/serialize.ts\nfunction workflowTriggerRaw(run) {\n\tif (run.sourceKind === \"gateway\") return \"gateway\";\n\treturn run.trigger;\n}\nfunction agentTriggerRaw(session) {\n\treturn session.sourceKind;\n}\nfunction workflowTriggerRawFromParts(run, override) {\n\treturn override ?? workflowTriggerRaw(run);\n}\nfunction agentTriggerRawFromParts(session, override) {\n\treturn override ?? agentTriggerRaw(session);\n}\nfunction durationMsBetween(startedAt, finishedAt) {\n\tif (!startedAt || !finishedAt) return null;\n\treturn Math.max(0, finishedAt.getTime() - startedAt.getTime());\n}\nfunction historyRunFromWorkflow(parts) {\n\tconst { run, workflow, stepCount } = parts;\n\tconst resourceKey = run.workflowSlug;\n\tconst resourceId = workflow?.id ?? run.workflowSlug;\n\tconst resourceName = titleCaseResourceName(resourceKey, workflow?.name);\n\tconst status = run.status;\n\tconst startedAt = run.startedAt ?? run.triggeredAt;\n\tconst triggerRaw = workflowTriggerRawFromParts(run, parts.triggerRaw);\n\treturn {\n\t\tid: run.id,\n\t\tkind: \"workflow\",\n\t\ttraceId: run.triggerRunId ?? run.id,\n\t\tprojectId: run.projectId,\n\t\tresourceKey,\n\t\tresourceId,\n\t\tresourceName,\n\t\tstatus,\n\t\ttriggeredAt: run.triggeredAt.toISOString(),\n\t\ttimeInQueueMs: timeInQueueMsBetween(run.triggeredAt, run.startedAt),\n\t\tstartedAt: startedAt.toISOString(),\n\t\tfinishedAt: run.finishedAt?.toISOString() ?? null,\n\t\tdurationMs: durationMsBetween(startedAt, run.finishedAt),\n\t\ttriggerLabel: triggerLabelFromRaw(triggerRaw),\n\t\ttriggerRaw,\n\t\tranByUserId: run.ranByUserId ?? null,\n\t\tmodelsUsed: parts.modelsUsed ?? [],\n\t\totherServicesUsed: parts.otherServicesUsed ?? [],\n\t\ttotalCostUsd: parts.totalCostUsd ?? 0,\n\t\tstepCount\n\t};\n}\nfunction historyRunFromAgent(parts) {\n\tconst { session, agent, status, messageCount } = parts;\n\tconst resourceKey = agent.slug;\n\tconst triggerRaw = agentTriggerRawFromParts(session, parts.triggerRaw);\n\tconst startedAt = session.createdAt;\n\tconst finishedAt = status === \"running\" ? null : session.canceledAt ?? session.updatedAt;\n\treturn {\n\t\tid: session.id,\n\t\tkind: \"agent\",\n\t\ttraceId: session.id,\n\t\tprojectId: session.projectId,\n\t\tresourceKey,\n\t\tresourceId: agent.id,\n\t\tresourceName: titleCaseResourceName(resourceKey, agent.name),\n\t\tstatus,\n\t\ttriggeredAt: session.createdAt.toISOString(),\n\t\ttimeInQueueMs: null,\n\t\tstartedAt: startedAt.toISOString(),\n\t\tfinishedAt: finishedAt?.toISOString() ?? null,\n\t\tdurationMs: parts.totalDurationMs ?? 0,\n\t\ttriggerLabel: triggerLabelFromRaw(triggerRaw),\n\t\ttriggerRaw,\n\t\tranByUserId: session.ranByUserId ?? null,\n\t\tmodelsUsed: parts.modelsUsed ?? [],\n\t\totherServicesUsed: parts.otherServicesUsed ?? [],\n\t\ttotalCostUsd: parts.totalCostUsd ?? 0,\n\t\tmessageCount\n\t};\n}\nfunction mapTrace(trace, messageEvents = []) {\n\treturn {\n\t\ttraceId: trace.traceId,\n\t\ttrigger: trace.trigger ? {\n\t\t\ttriggerType: trace.trigger.triggerType,\n\t\t\ttriggerRunId: trace.trigger.triggerRunId,\n\t\t\t...trace.trigger.workflowSlug ? { workflowKey: trace.trigger.workflowSlug } : {},\n\t\t\t...trace.trigger.agentSlug ? { agentKey: trace.trigger.agentSlug } : {},\n\t\t\tattachmentId: trace.trigger.attachmentId ?? null,\n\t\t\tattachmentSlug: trace.trigger.attachmentSlug ?? null,\n\t\t\troute: trace.trigger.route,\n\t\t\tsourcePath: trace.trigger.sourcePath ?? null\n\t\t} : null,\n\t\tgateway: trace.gateway,\n\t\tspans: attachMessagesToAgentSessionSpans(trace.spans, messageEvents),\n\t\tlogs: trace.logs\n\t};\n}\nasync function buildHistoryWorkflowRunDetail(workflowSlug, runId) {\n\tconst detail = await buildWorkflowRunDetail({\n\t\tworkflowSlug,\n\t\trunId,\n\t\tinclude: [\n\t\t\t\"trigger\",\n\t\t\t\"steps\",\n\t\t\t\"trace\"\n\t\t]\n\t});\n\tif (!detail) return null;\n\tconst durationMs = durationMsBetween(detail.run.startedAt ? new Date(detail.run.startedAt) : null, detail.run.finishedAt ? new Date(detail.run.finishedAt) : null);\n\tconst usageRecords = await listUsageRecordsForRun(runId, \"workflow\");\n\treturn {\n\t\tkind: \"workflow\",\n\t\trun: {\n\t\t\tid: detail.run.id,\n\t\t\tworkflowKey: detail.run.workflowSlug,\n\t\t\tstatus: detail.run.status,\n\t\t\ttrigger: detail.run.trigger,\n\t\t\ttriggeredAt: detail.run.triggeredAt,\n\t\t\tstartedAt: detail.run.startedAt,\n\t\t\tfinishedAt: detail.run.finishedAt,\n\t\t\tinput: detail.run.input,\n\t\t\toutput: detail.run.output,\n\t\t\terror: detail.run.error\n\t\t},\n\t\ttrigger: detail.trigger ? {\n\t\t\tid: detail.trigger.id,\n\t\t\tattachmentSlug: detail.trigger.attachmentSlug,\n\t\t\ttriggerType: detail.trigger.triggerType,\n\t\t\tsourcePath: detail.trigger.sourcePath,\n\t\t\tpayload: detail.trigger.payload,\n\t\t\ttriggeredAt: detail.trigger.triggeredAt\n\t\t} : null,\n\t\tsteps: detail.steps,\n\t\ttrace: detail.trace ? mapTrace(detail.trace) : null,\n\t\tusage: buildHistoryUsage(usageRecords.map((record) => ({\n\t\t\tkind: record.kind,\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amount\n\t\t})), durationMs)\n\t};\n}\nasync function buildHistoryAgentSessionDetail(agentSlug, sessionId) {\n\tconst [detail, messageEvents] = await Promise.all([buildAgentSessionDetail({\n\t\tagentSlug,\n\t\tsessionId,\n\t\tinclude: [\"gateway\", \"trace\"]\n\t}), listMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE)]);\n\tif (!detail) return null;\n\tconst usageRecords = await listUsageRecordsForRun(sessionId, \"agent\");\n\treturn {\n\t\tkind: \"agent\",\n\t\trunId: detail.session.id,\n\t\tsession: {\n\t\t\tid: detail.session.id,\n\t\t\tagentKey: detail.session.agentSlug,\n\t\t\tstatus: detail.session.status,\n\t\t\tsource: detail.session.source,\n\t\t\tsourceId: detail.session.sourceId,\n\t\t\tcreatedAt: detail.session.createdAt,\n\t\t\tupdatedAt: detail.session.updatedAt,\n\t\t\tmessageCount: detail.session.messageCount,\n\t\t\terror: detail.session.error\n\t\t},\n\t\tgateway: detail.gateway ? {\n\t\t\tthreadId: detail.gateway.threadId,\n\t\t\tattachmentSlug: detail.gateway.attachmentSlug\n\t\t} : null,\n\t\tmessages: messageEvents.map((event) => event.payload),\n\t\ttrace: detail.trace ? mapTrace(detail.trace, messageEvents) : null,\n\t\tusage: buildHistoryUsage(usageRecords.map((record) => ({\n\t\t\tkind: record.kind,\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amount\n\t\t})), detail.session.totalDurationMs ?? null)\n\t};\n}\n//#endregion\n//#region src/queries/history/internal.ts\nasync function countStepCompletedEventsByRunIds(runIds) {\n\tif (runIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\trunId: workflowEvents.runId,\n\t\tcount: sql$1`count(*)`\n\t}).from(workflowEvents).where(and$1(inArray$1(workflowEvents.runId, runIds), eq$1(workflowEvents.type, \"step_completed\"))).groupBy(workflowEvents.runId);\n\treturn new Map(rows.map((row) => [row.runId, Number(row.count ?? 0)]));\n}\nasync function countStepCompletedEvents(runId) {\n\treturn (await countStepCompletedEventsByRunIds([runId])).get(runId) ?? 0;\n}\nasync function countMessageEventsBySessionIds(sessionIds, messageEventType) {\n\tif (sessionIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tsessionId: agentEvents.sessionId,\n\t\tcount: sql$1`count(*)`\n\t}).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(and$1(inArray$1(agentEvents.sessionId, sessionIds), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt))).groupBy(agentEvents.sessionId);\n\treturn new Map(rows.map((row) => [row.sessionId, Number(row.count ?? 0)]));\n}\nasync function selectTriggerTypesByIds(ids) {\n\tif (ids.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tid: triggerRuns.id,\n\t\ttriggerType: triggerRuns.triggerType\n\t}).from(triggerRuns).where(inArray$1(triggerRuns.id, ids));\n\treturn new Map(rows.map((row) => [row.id, row.triggerType]));\n}\nfunction resolveWorkflowTriggerRaw(run, triggerTypes) {\n\tif (run.sourceKind === \"gateway\") return \"gateway\";\n\tif (run.sourceKind === \"trigger\" && run.triggerRunId) {\n\t\tconst triggerType = triggerTypes.get(run.triggerRunId);\n\t\tif (triggerType) return triggerType;\n\t}\n\treturn run.trigger;\n}\nfunction resolveAgentTriggerRaw(session, triggerTypes) {\n\tif (session.sourceKind === \"trigger\" && session.sourceId) {\n\t\tconst triggerType = triggerTypes.get(session.sourceId);\n\t\tif (triggerType) return triggerType;\n\t}\n\tif (session.sourceKind === \"gateway\") return \"gateway\";\n\treturn session.sourceKind;\n}\nfunction otherServicesUsedByRunId(records) {\n\tconst byRunId = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tif (record.kind === \"llm\") continue;\n\t\tconst kinds = byRunId.get(record.runId) ?? /* @__PURE__ */ new Set();\n\t\tkinds.add(record.kind);\n\t\tbyRunId.set(record.runId, kinds);\n\t}\n\treturn new Map([...byRunId.entries()].map(([runId, kinds]) => [runId, [...kinds]]));\n}\nfunction workflowUsageRollupsByRunId(records) {\n\tconst byRunId = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst entry = byRunId.get(record.runId) ?? {\n\t\t\ttotalCostUsd: 0,\n\t\t\tmodelsUsed: /* @__PURE__ */ new Set()\n\t\t};\n\t\tentry.totalCostUsd += record.amount;\n\t\tif (record.kind === \"llm\") entry.modelsUsed.add(record.label);\n\t\tbyRunId.set(record.runId, entry);\n\t}\n\treturn new Map([...byRunId.entries()].map(([runId, entry]) => [runId, {\n\t\ttotalCostUsd: entry.totalCostUsd,\n\t\tmodelsUsed: [...entry.modelsUsed]\n\t}]));\n}\nasync function selectLatestAgentSessionSpansByRefIds(sessionIds) {\n\tif (sessionIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tspan: traceSpans,\n\t\trefId: traceSpans.refId\n\t}).from(traceSpans).innerJoin(agentSessions, eq$1(agentSessions.id, traceSpans.refId)).where(and$1(inArray$1(traceSpans.refId, sessionIds), eq$1(traceSpans.kind, \"agent_session\"), isNull(agentSessions.deletedAt))).orderBy(desc(traceSpans.startedAt));\n\tconst latestByRefId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (!latestByRefId.has(row.refId)) latestByRefId.set(row.refId, row.span);\n\treturn latestByRefId;\n}\nfunction historyProjectConditions(column, filter) {\n\tif (filter?.projectIds !== void 0) {\n\t\tif (filter.projectIds.length === 0) return [];\n\t\treturn [inArray$1(column, filter.projectIds)];\n\t}\n\treturn [];\n}\nfunction resolveFetchLimit(limit, status) {\n\tif (!status) return limit;\n\treturn Math.min(limit * 5, 500);\n}\nfunction matchesStatusFilter(actual, filter) {\n\tif (filter === \"running\") return actual === \"running\" || actual === \"pending\";\n\treturn actual === filter;\n}\n//#endregion\n//#region src/queries/history/list-runs.ts\nasync function listWorkflowHistoryRuns(options, fetchLimit) {\n\tconst filter = options.projectIds !== void 0 ? { projectIds: options.projectIds } : void 0;\n\tconst conditions = historyProjectConditions(workflowRuns.projectId, filter);\n\tif (filter?.projectIds !== void 0 && filter.projectIds.length === 0) return [];\n\tif (options.workflow) {\n\t\tconditions.push(eq$1(workflowRuns.projectId, options.workflow.projectId));\n\t\tconditions.push(eq$1(workflowRuns.workflowSlug, options.workflow.slug));\n\t}\n\tconst db = getDb();\n\tconst rows = await (conditions.length > 0 ? db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt))).where(and$1(...conditions)) : db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt)))).orderBy(desc(workflowRuns.triggeredAt), desc(workflowRuns.id)).limit(fetchLimit);\n\tconst runIds = rows.map((row) => row.run.id);\n\tconst triggerRunIds = rows.map((row) => row.run.sourceKind === \"trigger\" ? row.run.triggerRunId : null).filter((id) => Boolean(id));\n\tconst [stepCounts, triggerTypes, usageRecords] = await Promise.all([\n\t\tcountStepCompletedEventsByRunIds(runIds),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tlistUsageRecordsForRuns(runIds, \"workflow\")\n\t]);\n\tconst usageRollups = workflowUsageRollupsByRunId(usageRecords);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords);\n\treturn rows.map((row) => {\n\t\tconst rollups = usageRollups.get(row.run.id);\n\t\treturn historyRunFromWorkflow({\n\t\t\trun: row.run,\n\t\t\tworkflow: row.workflow,\n\t\t\tstepCount: stepCounts.get(row.run.id) ?? 0,\n\t\t\ttriggerRaw: resolveWorkflowTriggerRaw(row.run, triggerTypes),\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed: otherServicesUsed.get(row.run.id) ?? []\n\t\t});\n\t});\n}\nasync function listAgentHistoryRuns(filter, fetchLimit) {\n\tif (filter?.projectIds !== void 0 && filter.projectIds.length === 0) return [];\n\tconst db = getDb();\n\tconst conditions = [isNull(agentSessions.deletedAt), isNull(agents.deletedAt)];\n\tif (filter?.projectIds !== void 0) conditions.push(inArray$1(agentSessions.projectId, filter.projectIds));\n\tconst rows = await db.select({\n\t\tsession: agentSessions,\n\t\tagent: agents\n\t}).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(...conditions)).orderBy(desc(agentSessions.updatedAt), desc(agentSessions.id)).limit(fetchLimit);\n\tconst sessionIds = rows.map((row) => row.session.id);\n\tconst triggerRunIds = rows.map((row) => row.session.sourceKind === \"trigger\" ? row.session.sourceId : null).filter((id) => Boolean(id));\n\tconst [messageCounts, triggerTypes, spansBySessionId, usageRecords] = await Promise.all([\n\t\tcountMessageEventsBySessionIds(sessionIds, MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tselectLatestAgentSessionSpansByRefIds(sessionIds),\n\t\tlistUsageRecordsForRuns(sessionIds, \"agent\")\n\t]);\n\tconst usageRollups = workflowUsageRollupsByRunId(usageRecords);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords);\n\treturn rows.map((row) => {\n\t\tconst messageCount = messageCounts.get(row.session.id) ?? 0;\n\t\tconst span = spansBySessionId.get(row.session.id);\n\t\tconst rollups = usageRollups.get(row.session.id);\n\t\treturn historyRunFromAgent({\n\t\t\tsession: row.session,\n\t\t\tagent: row.agent,\n\t\t\tstatus: agentSessionStatusFromSpan(span, messageCount, row.session.canceledAt),\n\t\t\tmessageCount,\n\t\t\ttriggerRaw: resolveAgentTriggerRaw(row.session, triggerTypes),\n\t\t\ttotalDurationMs: row.session.totalDurationMs,\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed: otherServicesUsed.get(row.session.id) ?? []\n\t\t});\n\t});\n}\nfunction sortHistoryRuns(items) {\n\treturn [...items].sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());\n}\nasync function listHistoryRuns(options = {}) {\n\tconst limit = options.limit ?? 100;\n\tconst fetchLimit = resolveFetchLimit(limit, options.status);\n\tconst includeWorkflows = options.kind !== \"agent\";\n\tconst includeAgents = options.kind !== \"workflow\";\n\tconst projectFilter = options.projectIds !== void 0 ? { projectIds: options.projectIds } : void 0;\n\tconst [workflowItems, agentItems] = await Promise.all([includeWorkflows ? listWorkflowHistoryRuns(options, fetchLimit) : Promise.resolve([]), includeAgents ? listAgentHistoryRuns(projectFilter, fetchLimit) : Promise.resolve([])]);\n\tlet items = sortHistoryRuns([...workflowItems, ...agentItems]);\n\tif (options.status) items = items.filter((item) => matchesStatusFilter(item.status, options.status));\n\treturn items.slice(0, limit);\n}\n//#endregion\n//#region src/queries/history/find-run-core.ts\nasync function findHistoryRunCore(runId) {\n\tconst db = getDb();\n\tconst workflowRow = (await db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt))).where(eq$1(workflowRuns.id, runId)).limit(1))[0];\n\tif (workflowRow) {\n\t\tconst [stepCount, triggerTypes, usageRecords] = await Promise.all([\n\t\t\tcountStepCompletedEvents(workflowRow.run.id),\n\t\t\tselectTriggerTypesByIds(workflowRow.run.sourceKind === \"trigger\" && workflowRow.run.triggerRunId ? [workflowRow.run.triggerRunId] : []),\n\t\t\tlistUsageRecordsForRuns([workflowRow.run.id], \"workflow\")\n\t\t]);\n\t\tconst rollups = workflowUsageRollupsByRunId(usageRecords).get(workflowRow.run.id);\n\t\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords).get(workflowRow.run.id) ?? [];\n\t\treturn historyRunFromWorkflow({\n\t\t\trun: workflowRow.run,\n\t\t\tworkflow: workflowRow.workflow,\n\t\t\tstepCount,\n\t\t\ttriggerRaw: resolveWorkflowTriggerRaw(workflowRow.run, triggerTypes),\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed\n\t\t});\n\t}\n\tconst agentRow = (await db.select({\n\t\tsession: agentSessions,\n\t\tagent: agents\n\t}).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(eq$1(agentSessions.id, runId), isNull(agentSessions.deletedAt), isNull(agents.deletedAt))).limit(1))[0];\n\tif (!agentRow) return null;\n\tconst sessionId = agentRow.session.id;\n\tconst [messageCounts, triggerTypes, spansBySessionId, usageRecords] = await Promise.all([\n\t\tcountMessageEventsBySessionIds([sessionId], MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(agentRow.session.sourceKind === \"trigger\" && agentRow.session.sourceId ? [agentRow.session.sourceId] : []),\n\t\tselectLatestAgentSessionSpansByRefIds([sessionId]),\n\t\tlistUsageRecordsForRuns([sessionId], \"agent\")\n\t]);\n\tconst messageCount = messageCounts.get(sessionId) ?? 0;\n\tconst span = spansBySessionId.get(sessionId);\n\tconst rollups = workflowUsageRollupsByRunId(usageRecords).get(sessionId);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords).get(sessionId) ?? [];\n\treturn historyRunFromAgent({\n\t\tsession: agentRow.session,\n\t\tagent: agentRow.agent,\n\t\tstatus: agentSessionStatusFromSpan(span, messageCount, agentRow.session.canceledAt),\n\t\tmessageCount,\n\t\ttriggerRaw: resolveAgentTriggerRaw(agentRow.session, triggerTypes),\n\t\ttotalDurationMs: agentRow.session.totalDurationMs,\n\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\totherServicesUsed\n\t});\n}\n//#endregion\n//#region src/queries/credential-instances/index.ts\n/** Org/user credentials live once in the shared org database; project scope stays per-project. */\nfunction credentialScopeAnd(scopeType, ...conditions) {\n\tif (scopeType === \"project\") return scopedAnd(credentialInstances, ...conditions);\n\treturn and$1(...conditions.filter(Boolean));\n}\nfunction resolveCredentialProjectId(scopeType) {\n\tif (scopeType === \"project\") return projectScopeId();\n\treturn getServerTenantScopeId();\n}\n/** Every credential instance row in the org database (org/user rows plus all projects' rows). */\nasync function listAllCredentialInstances() {\n\treturn getDb().select().from(credentialInstances);\n}\nasync function listCredentialInstancesByConnectionId(connectionId) {\n\treturn getDb().select().from(credentialInstances).where(eq$1(credentialInstances.connectionId, connectionId));\n}\nasync function selectCredentialInstanceById(id) {\n\treturn (await getDb().select().from(credentialInstances).where(eq$1(credentialInstances.id, id)).limit(1))[0];\n}\nasync function listCredentialInstancesByScope(options) {\n\tconst db = getDb();\n\tconst conditions = [options.scopeId === null ? and$1(eq$1(credentialInstances.scopeType, options.scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, options.scopeType), eq$1(credentialInstances.scopeId, options.scopeId))];\n\tif (options.appSlug) conditions.push(eq$1(credentialInstances.appSlug, options.appSlug));\n\treturn db.select().from(credentialInstances).where(credentialScopeAnd(options.scopeType, ...conditions));\n}\nasync function selectCredentialInstancesForScope(appSlug, scopeType, scopeId) {\n\tconst db = getDb();\n\tconst scopeCondition = scopeId === null ? and$1(eq$1(credentialInstances.scopeType, scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, scopeType), eq$1(credentialInstances.scopeId, scopeId));\n\treturn db.select().from(credentialInstances).where(credentialScopeAnd(scopeType, eq$1(credentialInstances.appSlug, appSlug), scopeCondition));\n}\nasync function insertCredentialInstance(values) {\n\tawait getDb().insert(credentialInstances).values({\n\t\t...values,\n\t\tprojectId: resolveCredentialProjectId(values.scopeType),\n\t\tisDefault: values.isDefault ? 1 : 0,\n\t\tgrantedScopes: values.grantedScopes ?? null\n\t});\n}\nasync function upsertCredentialInstance(values) {\n\tif (await selectCredentialInstanceById(values.id)) {\n\t\tawait getDb().update(credentialInstances).set({\n\t\t\tappSlug: values.appSlug,\n\t\t\tslug: values.slug,\n\t\t\tname: values.name ?? null,\n\t\t\tscopeType: values.scopeType,\n\t\t\tscopeId: values.scopeId,\n\t\t\tlabel: values.label,\n\t\t\tisDefault: values.isDefault ? 1 : 0,\n\t\t\tauthKind: values.authKind,\n\t\t\tciphertext: values.ciphertext,\n\t\t\tconnectionId: values.connectionId,\n\t\t\tsharedConnectionId: values.sharedConnectionId,\n\t\t\t...values.grantedScopes !== void 0 ? { grantedScopes: values.grantedScopes } : {},\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(credentialInstances.id, values.id));\n\t\treturn;\n\t}\n\tawait insertCredentialInstance(values);\n}\n/** Record that a credential was just resolved/used. Targeted by id; never throws on a missing row. */\nasync function touchCredentialInstanceLastUsed(id) {\n\tawait getDb().update(credentialInstances).set({ lastUsedAt: /* @__PURE__ */ new Date() }).where(eq$1(credentialInstances.id, id));\n}\nasync function deleteCredentialInstanceById(id) {\n\tif (!await selectCredentialInstanceById(id)) return false;\n\tawait getDb().delete(credentialInstances).where(eq$1(credentialInstances.id, id));\n\treturn true;\n}\nasync function clearCredentialInstanceDefaults(options) {\n\tconst db = getDb();\n\tconst scopeCondition = options.scopeId === null ? and$1(eq$1(credentialInstances.scopeType, options.scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, options.scopeType), eq$1(credentialInstances.scopeId, options.scopeId));\n\tconst conditions = [\n\t\teq$1(credentialInstances.appSlug, options.appSlug),\n\t\tscopeCondition,\n\t\teq$1(credentialInstances.isDefault, 1)\n\t];\n\tif (options.exceptId) conditions.push(ne(credentialInstances.id, options.exceptId));\n\tawait db.update(credentialInstances).set({\n\t\tisDefault: 0,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(credentialScopeAnd(options.scopeType, ...conditions));\n}\n//#endregion\n//#region src/queries/credential-assignments/index.ts\nasync function listCredentialAssignmentsByTarget(options) {\n\treturn getDb().select().from(credentialAssignments).where(scopedAnd(credentialAssignments, eq$1(credentialAssignments.targetType, options.targetType), eq$1(credentialAssignments.targetKey, options.targetKey)));\n}\nasync function selectCredentialAssignmentById(id) {\n\treturn (await getDb().select().from(credentialAssignments).where(scopedAnd(credentialAssignments, eq$1(credentialAssignments.id, id))).limit(1))[0];\n}\nasync function upsertCredentialAssignment(values) {\n\tconst db = getDb();\n\tconst id = values.id ?? crypto.randomUUID();\n\tconst now = values.updatedAt;\n\tconst projectId = projectScopeId();\n\treturn (await db.insert(credentialAssignments).values({\n\t\tid,\n\t\tprojectId,\n\t\ttargetType: values.targetType,\n\t\ttargetKey: values.targetKey,\n\t\tconsumerId: values.consumerId,\n\t\tcredentialSlug: values.credentialSlug,\n\t\tinstanceId: values.instanceId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).onConflictDoUpdate({\n\t\ttarget: [\n\t\t\tcredentialAssignments.projectId,\n\t\t\tcredentialAssignments.targetType,\n\t\t\tcredentialAssignments.targetKey,\n\t\t\tcredentialAssignments.consumerId,\n\t\t\tcredentialAssignments.credentialSlug\n\t\t],\n\t\tset: {\n\t\t\tinstanceId: values.instanceId,\n\t\t\tupdatedAt: now\n\t\t}\n\t}).returning())[0];\n}\nasync function deleteCredentialAssignmentById(id) {\n\tif (!await selectCredentialAssignmentById(id)) return false;\n\tawait getDb().delete(credentialAssignments).where(eq$1(credentialAssignments.id, id));\n\treturn true;\n}\n/**\n* Strip the per-occurrence suffix from a step correlation id so a loop's\n* iterations collapse to one consumer: `step:<callSiteId>#3` → `step:<callSiteId>`.\n* Credential bindings are keyed by the occurrence-independent call-site id, the\n* same key the workflow-canvas credential overlay uses (one binding per node).\n*/\nfunction stepConsumerId(correlationId) {\n\tconst hash = correlationId.lastIndexOf(\"#\");\n\treturn hash === -1 ? correlationId : correlationId.slice(0, hash);\n}\n/**\n* Distinct occurrence-independent step consumer ids (`step:<callSiteId>`) from\n* recent completed workflow runs — the credential-assignment consumer keys.\n*/\nasync function listRecentWorkflowStepConsumers(workflowSlug, runLimit = 5) {\n\tconst db = getDb();\n\tconst runIds = (await db.select({ id: workflowRuns.id }).from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.workflowSlug, workflowSlug))).orderBy(desc(workflowRuns.triggeredAt)).limit(runLimit)).map((row) => row.id);\n\tif (runIds.length === 0) return [];\n\tconst events = await db.select({ correlationId: workflowEvents.correlationId }).from(workflowEvents).where(scopedAnd(workflowEvents, inArray$1(workflowEvents.runId, runIds), eq$1(workflowEvents.type, \"step_completed\")));\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst consumers = [];\n\tfor (const event of events) {\n\t\tif (!event.correlationId) continue;\n\t\tconst id = stepConsumerId(event.correlationId);\n\t\tif (seen.has(id)) continue;\n\t\tseen.add(id);\n\t\tconsumers.push(id);\n\t}\n\treturn consumers;\n}\nasync function listDistinctAssignmentConsumerIds(options) {\n\tconst rows = await listCredentialAssignmentsByTarget(options);\n\treturn [...new Set(rows.map((row) => row.consumerId))];\n}\n//#endregion\n//#region src/queries/trace-spans/index.ts\nfunction traceRootJoins$1(rootId) {\n\treturn {\n\t\tworkflowRuns: eq$1(workflowRuns.id, rootId),\n\t\ttriggerRuns: eq$1(triggerRuns.id, rootId),\n\t\tagentSessions: eq$1(agentSessions.id, rootId)\n\t};\n}\nasync function insertTraceSpan(values) {\n\tawait getDb().insert(traceSpans).values({\n\t\t...values,\n\t\tparentSpanId: values.parentSpanId ?? null,\n\t\tfinishedAt: values.finishedAt ?? null,\n\t\tmetadata: values.metadata ?? null,\n\t\terror: values.error ?? null\n\t});\n}\nasync function updateTraceSpanStatus(id, status, finishedAt, error) {\n\tif (!await selectTraceSpanById(id)) return;\n\tawait getDb().update(traceSpans).set({\n\t\tstatus,\n\t\tfinishedAt,\n\t\terror: error ?? null\n\t}).where(eq$1(traceSpans.id, id));\n}\nasync function selectTraceSpanById(id) {\n\tconst db = getDb();\n\tconst rows = await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, eq$1(workflowRuns.id, traceSpans.traceId)).leftJoin(triggerRuns, eq$1(triggerRuns.id, traceSpans.traceId)).leftJoin(agentSessions, eq$1(agentSessions.id, traceSpans.traceId)).where(and$1(eq$1(traceSpans.id, id), traceRootProjectScopeFilter())).limit(1);\n\tif (rows[0]) return rows[0].span;\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, eq$1(workflowRuns.id, traceSpans.refId)).leftJoin(triggerRuns, eq$1(triggerRuns.id, traceSpans.refId)).leftJoin(agentSessions, eq$1(agentSessions.id, traceSpans.refId)).where(and$1(eq$1(traceSpans.id, id), traceRootProjectScopeFilter())).limit(1))[0]?.span;\n}\nasync function selectTraceSpanByRefId(refId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(refId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.refId, refId), traceRootProjectScopeFilter())).limit(1))[0]?.span;\n}\nasync function selectLatestAgentSessionSpanByRefId(refId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(refId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.refId, refId), eq$1(traceSpans.kind, \"agent_session\"), traceRootProjectScopeFilter())).orderBy(desc(traceSpans.startedAt)).limit(1))[0]?.span;\n}\nasync function listTraceSpansByTraceId(traceId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(traceId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.traceId, traceId), traceRootProjectScopeFilter())).orderBy(asc(traceSpans.startedAt))).map((row) => row.span);\n}\nasync function maxTraceLogSeq(traceId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(traceId);\n\treturn (await db.select({ value: max$1(traceLogs.seq) }).from(traceLogs).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceLogs.traceId, traceId), traceRootProjectScopeFilter())))[0]?.value ?? 0;\n}\n//#endregion\n//#region src/queries/trace-logs/index.ts\nfunction traceRootJoins(rootId) {\n\treturn {\n\t\tworkflowRuns: eq$1(workflowRuns.id, rootId),\n\t\ttriggerRuns: eq$1(triggerRuns.id, rootId),\n\t\tagentSessions: eq$1(agentSessions.id, rootId)\n\t};\n}\nasync function insertTraceLogs(values) {\n\tif (values.length === 0) return;\n\tawait getDb().insert(traceLogs).values(values.map((entry) => ({\n\t\t...entry,\n\t\tdata: entry.data ?? null\n\t})));\n}\nasync function listTraceLogsByTraceId(traceId, options) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins(traceId);\n\tconst conditions = [eq$1(traceLogs.traceId, traceId), traceRootProjectScopeFilter()];\n\tif (options?.spanId) conditions.push(eq$1(traceLogs.spanId, options.spanId));\n\tif (options?.afterSeq !== void 0) conditions.push(gt(traceLogs.seq, options.afterSeq));\n\tlet rows = await db.select({ log: traceLogs }).from(traceLogs).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(...conditions)).orderBy(asc(traceLogs.seq));\n\trows = rows.map((row) => ({ log: row.log }));\n\tif (options?.limit !== void 0) rows = rows.slice(0, options.limit);\n\treturn rows.map((row) => row.log);\n}\n//#endregion\n//#region src/runs/source.ts\nfunction runSource(kind, id) {\n\treturn {\n\t\tkind,\n\t\tid: id ?? null\n\t};\n}\nfunction sourceFromSpan(span) {\n\tswitch (span.kind) {\n\t\tcase \"workflow_run\": return runSource(\"workflow\", span.refId);\n\t\tcase \"agent_session\": return runSource(\"agent\", span.refId);\n\t\tcase \"trigger_run\": return runSource(\"trigger\", span.refId);\n\t\tcase \"gateway_event\": {\n\t\t\tconst metadata = span.metadata;\n\t\t\tif (metadata && typeof metadata === \"object\" && \"gatewayAttachmentId\" in metadata) {\n\t\t\t\tconst attachmentId = metadata.gatewayAttachmentId;\n\t\t\t\tif (typeof attachmentId === \"string\") return runSource(\"gateway\", attachmentId);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tcase \"action\": {\n\t\t\tconst metadata = span.metadata;\n\t\t\tif (metadata && typeof metadata === \"object\" && \"runId\" in metadata) {\n\t\t\t\tconst runId = metadata.runId;\n\t\t\t\tif (typeof runId === \"string\") return runSource(\"workflow\", runId);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tdefault: return;\n\t}\n}\nasync function resolveRunSourceFromTraceContext() {\n\tconst parent = getTraceContext();\n\tif (!parent?.spanId) return runSource(\"api\");\n\tconst span = await selectTraceSpanById(parent.spanId);\n\tif (!span) return runSource(\"api\");\n\treturn sourceFromSpan(span) ?? runSource(\"api\");\n}\n//#endregion\n//#region src/workflows/runs.ts\nfunction serializeError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\nfunction triggerRunType$1(trigger) {\n\treturn trigger;\n}\nfunction resolveWorkflowRunSource(input) {\n\tif (input.sourceKind) return runSource(input.sourceKind, input.sourceId);\n\tif (input.triggerRunId) return runSource(\"trigger\", input.triggerRunId);\n\tif (input.parentWorkflowRunId) return runSource(\"workflow\", input.parentWorkflowRunId);\n\treturn runSource(\"api\");\n}\nfunction workflowRunInsertValues(input, status) {\n\tconst source = resolveWorkflowRunSource(input);\n\tconst now = status === \"running\" ? /* @__PURE__ */ new Date() : null;\n\treturn {\n\t\tid: input.id,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId ?? null,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId: input.triggerRunId ?? null,\n\t\tparentWorkflowRunId: input.parentWorkflowRunId ?? null,\n\t\tparentSpanId: input.parentSpanId ?? null,\n\t\tsourceKind: source.kind,\n\t\tsourceId: source.id,\n\t\tranByUserId: input.ranByUserId ?? null,\n\t\tstatus,\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: now,\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t};\n}\nasync function createWorkflowRun(input) {\n\tawait insertWorkflowRun(workflowRunInsertValues(input, \"running\"));\n}\nasync function createPendingWorkflowRun(input) {\n\tawait insertWorkflowRun(workflowRunInsertValues(input, \"pending\"));\n}\nasync function markWorkflowRunRunning(id) {\n\tawait markWorkflowRunRunningRow(id, /* @__PURE__ */ new Date());\n}\nasync function markWorkflowRunSleeping(id) {\n\tawait setWorkflowRunStatusRow(id, \"sleeping\");\n}\nasync function markWorkflowRunWaitingHook(id) {\n\tawait setWorkflowRunStatusRow(id, \"waiting_hook\");\n}\nasync function completeWorkflowRun(id, output) {\n\tawait completeWorkflowRunRow(id, output, /* @__PURE__ */ new Date());\n}\nasync function failWorkflowRun(id, error) {\n\tawait failWorkflowRunRow(id, serializeError(error), /* @__PURE__ */ new Date());\n}\nasync function recordWorkflowLlmUsage(options) {\n\tconst { usage } = options;\n\tawait insertUsageRecord({\n\t\tid: crypto.randomUUID(),\n\t\trunId: options.workflowRunId,\n\t\trunKind: \"workflow\",\n\t\tkind: \"llm\",\n\t\tlabel: usage.label,\n\t\tquantity: usage.quantity,\n\t\tunit: \"tokens\",\n\t\tamount: usage.amount,\n\t\tmetadata: usage.metadata,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\nasync function finalizeCanceledWorkflowRun(id) {\n\tif (await cancelWorkflowRunRow(id, /* @__PURE__ */ new Date())) await appendWorkflowEvent({\n\t\tid: `run_canceled:${id}`,\n\t\trunId: id,\n\t\ttype: \"run_canceled\"\n\t});\n}\nasync function createAttachmentExecution(input) {\n\tconst triggerRunId = input.triggerRunId ?? crypto.randomUUID();\n\tconst workflowRunId = crypto.randomUUID();\n\tif (!input.triggerRunId) await insertTriggerRun({\n\t\tid: triggerRunId,\n\t\ttriggerId: input.triggerId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType$1(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertWorkflowRun({\n\t\tid: workflowRunId,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tstatus: \"running\",\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: /* @__PURE__ */ new Date(),\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t});\n\treturn {\n\t\tworkflowRunId,\n\t\ttriggerRunId\n\t};\n}\nasync function createPendingAttachmentExecution(input) {\n\tconst triggerRunId = input.triggerRunId ?? crypto.randomUUID();\n\tconst workflowRunId = crypto.randomUUID();\n\tif (!input.triggerRunId) await insertTriggerRun({\n\t\tid: triggerRunId,\n\t\ttriggerId: input.triggerId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType$1(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertWorkflowRun({\n\t\tid: workflowRunId,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tstatus: \"pending\",\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: null,\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t});\n\treturn {\n\t\tworkflowRunId,\n\t\ttriggerRunId\n\t};\n}\nasync function markAttachmentExecutionRunning(workflowRunId) {\n\tawait markWorkflowRunRunning(workflowRunId);\n}\n//#endregion\n//#region src/history/cancel.ts\nconst CANCELABLE_STATUSES = new Set([\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\"\n]);\nasync function cancelWorkflowRun(runId) {\n\tconst existing = await findHistoryRunCore(runId);\n\tif (!existing) return null;\n\tif (existing.kind !== \"workflow\") return existing;\n\tif (!CANCELABLE_STATUSES.has(existing.status)) return existing;\n\tawait finalizeCanceledWorkflowRun(runId);\n\treturn findHistoryRunCore(runId);\n}\nasync function cancelAgentSession(sessionId) {\n\tconst existing = await findHistoryRunCore(sessionId);\n\tif (!existing) return null;\n\tif (existing.kind !== \"agent\") return existing;\n\tif (existing.status === \"canceled\" || existing.status === \"completed\" || existing.status === \"failed\") return existing;\n\tawait cancelAgentSessionRow(sessionId, /* @__PURE__ */ new Date());\n\treturn findHistoryRunCore(sessionId);\n}\n//#endregion\n//#region src/agents/sync.ts\nfunction agentMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null,\n\t\ttoolCount: record.toolCount ?? null,\n\t\tcredentialCount: record.credentialCount ?? null,\n\t\tappSlugs: record.appSlugs ?? null\n\t};\n}\nasync function syncAgentRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst byRoute = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectAgentBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateAgentById(existing.id, {\n\t\t\t\troute: record.route,\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\tmodel: record.model,\n\t\t\t\tsystemPrompt: record.systemPrompt,\n\t\t\t\t...agentMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbyRoute.set(record.route, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertAgent({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\troute: record.route,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\tmodel: record.model,\n\t\t\tsystemPrompt: record.systemPrompt,\n\t\t\t...agentMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbyRoute.set(record.route, {\n\t\t\tid,\n\t\t\tslug: record.slug\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllAgents(now);\n\telse await softDeleteAgentsNotInSlugs(slugs, now);\n\treturn byRoute;\n}\nasync function getAgentByRoute(route) {\n\treturn selectActiveAgentByRoute(route);\n}\n//#endregion\n//#region src/agents/sessions.ts\nasync function createSession(agentId, id, source = runSource(\"api\"), options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst sessionId = id ?? crypto.randomUUID();\n\tawait insertAgentSession({\n\t\tid: sessionId,\n\t\tagentId,\n\t\tsourceKind: source.kind,\n\t\tsourceId: source.id,\n\t\tranByUserId: options?.ranByUserId ?? null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\treturn {\n\t\tid: sessionId,\n\t\tagentId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n}\nasync function getSession(sessionId) {\n\tconst row = await selectActiveAgentSession(sessionId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tagentId: row.agentId,\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt\n\t};\n}\nasync function touchSession(sessionId) {\n\tawait touchAgentSession(sessionId, /* @__PURE__ */ new Date());\n}\nasync function setSessionTitle(sessionId, title) {\n\tawait updateAgentSessionTitle(sessionId, title);\n}\nasync function nextSeq(sessionId) {\n\treturn await maxSeqForSession(sessionId) + 1;\n}\nasync function appendEvent(sessionId, eventType, payload) {\n\tconst seq = await nextSeq(sessionId);\n\tawait insertAgentEvent({\n\t\tid: crypto.randomUUID(),\n\t\tsessionId,\n\t\tseq,\n\t\teventType,\n\t\tpayload,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tdeletedAt: null\n\t});\n\treturn seq;\n}\nasync function listMessageEvents(sessionId) {\n\treturn listMessagePayloads(sessionId, MESSAGE_EVENT_TYPE);\n}\nasync function countMessageEvents(sessionId) {\n\treturn countMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE);\n}\nasync function listSessionEvents(sessionId) {\n\treturn (await listAgentEventsForSession(sessionId)).map((row) => ({\n\t\tid: row.id,\n\t\tsessionId: row.sessionId,\n\t\tseq: row.seq,\n\t\teventType: row.eventType,\n\t\tpayload: row.payload,\n\t\tcreatedAt: row.createdAt\n\t}));\n}\nasync function setSessionLiveMessage(sessionId, message) {\n\tawait updateSessionLiveMessage(sessionId, message);\n}\nasync function clearLiveMessage(sessionId) {\n\tawait clearSessionLiveMessage(sessionId);\n}\nasync function getSessionLiveMessage(sessionId) {\n\treturn selectSessionLiveMessage(sessionId);\n}\n//#endregion\n//#region src/agents/runs.ts\nasync function recordLlmUsageFromAssistantMessage(options) {\n\tconst { usage } = options;\n\tawait insertUsageRecord({\n\t\tid: crypto.randomUUID(),\n\t\trunId: options.sessionId,\n\t\trunKind: \"agent\",\n\t\tkind: \"llm\",\n\t\tlabel: usage.label,\n\t\tquantity: usage.quantity,\n\t\tunit: \"tokens\",\n\t\tamount: usage.amount,\n\t\tmetadata: usage.metadata,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\n//#endregion\n//#region src/agents/fail-session.ts\nfunction serializeSpanError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\n/**\n* Mark an agent session as failed by closing or inserting its terminal `agent_session`\n* trace span. History derives session status from that span.\n*/\nasync function failAgentSession(sessionId, error) {\n\tconst serializedError = serializeSpanError(error);\n\tconst finishedAt = /* @__PURE__ */ new Date();\n\tconst span = await selectLatestAgentSessionSpanByRefId(sessionId);\n\tif (span) {\n\t\tif (span.status !== \"running\") return;\n\t\tawait updateTraceSpanStatus(span.id, \"error\", finishedAt, serializedError);\n\t\treturn;\n\t}\n\tconst session = await selectAgentSessionById(sessionId);\n\tif (!session) return;\n\tawait insertTraceSpan({\n\t\tid: crypto.randomUUID(),\n\t\ttraceId: sessionId,\n\t\tkind: \"agent_session\",\n\t\trefId: sessionId,\n\t\tname: session.agentId,\n\t\tstatus: \"error\",\n\t\tstartedAt: finishedAt,\n\t\tfinishedAt,\n\t\tmetadata: {\n\t\t\tagentId: session.agentId,\n\t\t\ttrigger: \"api\"\n\t\t},\n\t\terror: serializedError\n\t});\n}\n//#endregion\n//#region src/skills/sync.ts\nfunction skillMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null\n\t};\n}\nasync function syncSkillRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst bySlug = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectSkillBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateSkillById(existing.id, {\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\t...skillMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbySlug.set(record.slug, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertSkill({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\t...skillMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbySlug.set(record.slug, {\n\t\t\tid,\n\t\t\tslug: record.slug\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllSkills(now);\n\telse await softDeleteSkillsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/triggers/source-slug.ts\n/** Read source slug from persisted JSON (`slug` preferred, legacy `key` fallback). */\nfunction storedTriggerSourceSlug(source) {\n\tconst slug = source.slug?.trim() || source.key?.trim();\n\tif (!slug) throw new Error(\"Stored trigger source requires slug or legacy key\");\n\treturn slug;\n}\n/** Write canonical persisted source JSON (uses `slug`; omits legacy `key`). */\nfunction normalizeStoredTriggerSource(source) {\n\tconst slug = storedTriggerSourceSlug(source);\n\tif (source.kind === \"webhook\") return {\n\t\tkind: \"webhook\",\n\t\tslug,\n\t\tendpoint: source.endpoint,\n\t\trequestSchema: source.requestSchema,\n\t\t...source.filterSchema ? { filterSchema: source.filterSchema } : {}\n\t};\n\tif (source.kind === \"cron\") return {\n\t\tkind: \"cron\",\n\t\tslug,\n\t\tschedule: source.schedule\n\t};\n\treturn {\n\t\tkind: \"poll\",\n\t\tslug,\n\t\tschedule: source.schedule,\n\t\t...source.code ? { code: source.code } : {},\n\t\t...source.id ? { id: source.id } : {}\n\t};\n}\n//#endregion\n//#region src/triggers/trigger-config.ts\nfunction triggerConfigFromSource(source) {\n\tif (source.kind === \"webhook\") return {\n\t\tendpoint: source.endpoint,\n\t\trequestSchema: source.requestSchema,\n\t\t...source.filterSchema ? { filterSchema: source.filterSchema } : {}\n\t};\n\tif (source.kind === \"poll\") return {\n\t\t...source.code ? { code: source.code } : {},\n\t\t...source.id ? { id: source.id } : {}\n\t};\n\treturn null;\n}\nfunction triggerScheduleFromSource(source) {\n\tif (source.kind === \"cron\" || source.kind === \"poll\") return source.schedule;\n\treturn null;\n}\n/** Stable key for grouping attachments that share the same trigger source. */\nfunction triggerSourceGroupKeyFromSource(source) {\n\tconst sourceSlug = storedTriggerSourceSlug(source);\n\tif (source.kind === \"poll\" && source.id) return `poll:${source.id}`;\n\treturn `${source.kind}:${sourceSlug}`;\n}\nfunction triggerSlugFromSource(source) {\n\treturn storedTriggerSourceSlug(normalizeStoredTriggerSource(source));\n}\nfunction webhookEndpointFromTriggerConfig(config) {\n\tif (config && \"endpoint\" in config) return config.endpoint;\n\treturn null;\n}\n/** Reconstruct the `StoredTriggerSource` JSON shape from a normalized `triggers` row. */\nfunction storedTriggerSourceFromTrigger(trigger) {\n\tconst meta = {\n\t\tname: trigger.name,\n\t\tdescription: trigger.description\n\t};\n\tif (trigger.kind === \"webhook\") {\n\t\tconst config = trigger.config ?? {};\n\t\treturn {\n\t\t\t...meta,\n\t\t\tkind: \"webhook\",\n\t\t\tslug: trigger.slug,\n\t\t\tendpoint: config.endpoint,\n\t\t\trequestSchema: config.requestSchema,\n\t\t\t...config.filterSchema ? { filterSchema: config.filterSchema } : {}\n\t\t};\n\t}\n\tif (trigger.kind === \"cron\") return {\n\t\t...meta,\n\t\tkind: \"cron\",\n\t\tslug: trigger.slug,\n\t\tschedule: trigger.schedule ?? \"\"\n\t};\n\tconst config = trigger.config ?? {};\n\treturn {\n\t\t...meta,\n\t\tkind: \"poll\",\n\t\tslug: trigger.slug,\n\t\tschedule: trigger.schedule ?? \"\",\n\t\t...config.code ? { code: config.code } : {},\n\t\t...config.id ? { id: config.id } : {}\n\t};\n}\n//#endregion\n//#region src/triggers/sync.ts\nfunction groupDiscoveredRecords(records) {\n\tconst groups = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst source = normalizeStoredTriggerSource(record.source);\n\t\tconst groupKey = triggerSourceGroupKeyFromSource(source);\n\t\tconst triggerSlug = triggerSlugFromSource(source);\n\t\tconst existing = groups.get(groupKey);\n\t\tif (existing) {\n\t\t\texisting.records.push(record);\n\t\t\tcontinue;\n\t\t}\n\t\tgroups.set(groupKey, {\n\t\t\tgroupKey,\n\t\t\ttriggerSlug,\n\t\t\trecords: [record]\n\t\t});\n\t}\n\treturn [...groups.values()];\n}\n/** Deterministic JSON with recursively sorted object keys, so the hash is stable. */\nfunction canonicalStringify(value) {\n\tif (Array.isArray(value)) return `[${value.map(canonicalStringify).join(\",\")}]`;\n\tif (value && typeof value === \"object\") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalStringify(v)}`).join(\",\")}}`;\n\treturn JSON.stringify(value ?? null);\n}\n/**\n* Hash of the inputs an LLM overview is derived from. Written to `triggers.triggerHash`\n* on every deploy; the overview is stale (and regenerated) when it diverges from the\n* worker-stamped `overviewHash`.\n*/\nfunction computeTriggerHash(group, source, schedule) {\n\tconst primary = group.records[0];\n\tconst assignments = group.records.map((record) => ({\n\t\ttargetKind: record.targetKind,\n\t\tworkflowSlug: record.workflowSlug ?? null,\n\t\tagentSlug: record.agentSlug ?? null\n\t})).sort((a, b) => canonicalStringify(a).localeCompare(canonicalStringify(b)));\n\treturn createHash(\"sha256\").update(canonicalStringify({\n\t\tname: primary.name,\n\t\tdescription: primary.description,\n\t\tkind: source.kind,\n\t\tschedule,\n\t\tconfig: triggerConfigFromSource(source),\n\t\tmoduleFile: primary.moduleFile,\n\t\tsourceHash: primary.sourceHash ?? null,\n\t\tassignments\n\t})).digest(\"hex\");\n}\nasync function syncTriggerAttachmentRegistry(records, options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst attachmentSlugs = records.map((record) => record.slug);\n\tconst triggerSlugs = [...new Set(records.map((record) => triggerSlugFromSource(record.source)))];\n\tconst byKey = /* @__PURE__ */ new Map();\n\tfor (const group of groupDiscoveredRecords(records)) {\n\t\tconst primary = group.records[0];\n\t\tconst source = normalizeStoredTriggerSource(primary.source);\n\t\tconst schedule = triggerScheduleFromSource(source);\n\t\tconst triggerHash = computeTriggerHash(group, source, schedule);\n\t\tconst existingTrigger = await selectTriggerBySlug(group.triggerSlug);\n\t\tlet triggerId;\n\t\tif (existingTrigger) {\n\t\t\ttriggerId = existingTrigger.id;\n\t\t\tawait updateTriggerById(existingTrigger.id, {\n\t\t\t\tname: primary.name,\n\t\t\t\tdescription: primary.description,\n\t\t\t\tmoduleFile: primary.moduleFile,\n\t\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\t\tschedule,\n\t\t\t\ttriggerHash,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t} else {\n\t\t\ttriggerId = crypto.randomUUID();\n\t\t\tawait insertTrigger({\n\t\t\t\tid: triggerId,\n\t\t\t\tslug: group.triggerSlug,\n\t\t\t\tkind: source.kind,\n\t\t\t\tname: primary.name,\n\t\t\t\tdescription: primary.description,\n\t\t\t\tmoduleFile: primary.moduleFile,\n\t\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\t\tschedule,\n\t\t\t\ttriggerHash,\n\t\t\t\torigin: \"project\",\n\t\t\t\tregisteredAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t}\n\t\tfor (const record of group.records) {\n\t\t\tconst existingAttachment = await selectTriggerAttachmentBySlug(record.slug);\n\t\t\tif (existingAttachment) {\n\t\t\t\tawait updateTriggerAttachmentById(existingAttachment.id, {\n\t\t\t\t\ttargetKind: record.targetKind,\n\t\t\t\t\tworkflowSlug: record.workflowSlug ?? null,\n\t\t\t\t\tagentSlug: record.agentSlug ?? null,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\tdeletedAt: null\n\t\t\t\t});\n\t\t\t\tbyKey.set(record.slug, {\n\t\t\t\t\tid: existingAttachment.id,\n\t\t\t\t\tslug: record.slug,\n\t\t\t\t\ttriggerId\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst attachmentId = crypto.randomUUID();\n\t\t\tawait insertTriggerAttachment({\n\t\t\t\tid: attachmentId,\n\t\t\t\ttriggerId,\n\t\t\t\tslug: record.slug,\n\t\t\t\ttargetKind: record.targetKind,\n\t\t\t\tworkflowSlug: record.workflowSlug ?? null,\n\t\t\t\tagentSlug: record.agentSlug ?? null,\n\t\t\t\tregisteredAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdisabledAt: null,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbyKey.set(record.slug, {\n\t\t\t\tid: attachmentId,\n\t\t\t\tslug: record.slug,\n\t\t\t\ttriggerId\n\t\t\t});\n\t\t}\n\t\tif (schedule && (source.kind === \"cron\" || source.kind === \"poll\")) {\n\t\t\tconst initialNextRunAt = options?.resolveInitialNextRunAt?.(schedule, source.kind, now) ?? now;\n\t\t\tconst executable = await listExecutableAttachmentsByTriggerIds([triggerId]);\n\t\t\tawait upsertTriggerScheduleFields({\n\t\t\t\ttriggerSlug: group.triggerSlug,\n\t\t\t\tschedule,\n\t\t\t\tnextRunAt: existingTrigger?.nextRunAt ?? initialNextRunAt,\n\t\t\t\tenabled: executable.length > 0,\n\t\t\t\tupdatedAt: now\n\t\t\t});\n\t\t}\n\t}\n\tif (attachmentSlugs.length === 0) {\n\t\tawait softDeleteAllProjectTriggers(now);\n\t\tawait softDeleteAllTriggerAttachments(now);\n\t} else {\n\t\tawait softDeleteTriggerAttachmentsNotInSlugs(attachmentSlugs, now);\n\t\tawait softDeleteProjectTriggersNotInSlugs(triggerSlugs, now);\n\t}\n\treturn byKey;\n}\n//#endregion\n//#region src/triggers/agent-runs.ts\nfunction triggerRunType(trigger) {\n\tif (trigger === \"cron\" || trigger === \"poll\" || trigger === \"webhook\") return trigger;\n\tthrow new Error(`Unexpected trigger type for trigger run: ${trigger}`);\n}\nasync function createAgentAttachmentExecution(input) {\n\tconst triggerRunId = input.triggerRunId ?? crypto.randomUUID();\n\tconst sessionId = crypto.randomUUID();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (!input.triggerRunId) await insertTriggerRun({\n\t\tid: triggerRunId,\n\t\ttriggerId: input.triggerId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertAgentSession({\n\t\tid: sessionId,\n\t\tagentId: input.agentId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\treturn {\n\t\ttriggerRunId,\n\t\tsessionId\n\t};\n}\nasync function getTriggerRunForAgentSession(sessionId) {\n\tconst session = await selectAgentSessionById(sessionId);\n\tif (session?.sourceKind !== \"trigger\" || !session.sourceId) return;\n\treturn selectTriggerRunById(session.sourceId);\n}\n//#endregion\n//#region src/triggers/fire.ts\n/** Persist a trigger fire that did not dispatch a downstream workflow run or agent session. */\nasync function recordTriggerFire(input) {\n\tconst id = crypto.randomUUID();\n\tawait insertTriggerRun({\n\t\tid,\n\t\ttriggerId: input.triggerId,\n\t\ttriggerType: input.triggerType,\n\t\toutcome: input.outcome,\n\t\treason: input.reason ?? null,\n\t\tdetail: input.detail ?? null,\n\t\tpayload: input.payload ?? null,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggeredAt: input.triggeredAt ?? /* @__PURE__ */ new Date()\n\t});\n\treturn id;\n}\n//#endregion\n//#region src/triggers/assignments.ts\nfunction triggerStatusFromRow(row, attachments) {\n\tif (row.deletedAt) return \"disabled\";\n\tconst lifecycleStatus = row.lifecycle?.status;\n\tif (lifecycleStatus === \"disabled\" || lifecycleStatus === \"completed\") return \"disabled\";\n\tif (attachments !== void 0) {\n\t\tif (!attachments.some((attachment) => triggerAttachmentStatusFromRow(attachment) === \"active\")) return \"disabled\";\n\t}\n\tif (row.kind === \"cron\" || row.kind === \"poll\") return row.enabled === 1 ? \"active\" : \"disabled\";\n\treturn \"active\";\n}\nfunction assignmentFromRow(row, trigger, target) {\n\treturn {\n\t\tkind: target.kind,\n\t\tid: target.id,\n\t\tslug: target.slug,\n\t\tname: target.name,\n\t\tattachmentId: row.id,\n\t\tattachmentSlug: row.slug,\n\t\tstatus: triggerAttachmentStatusFromRow(row),\n\t\tdisabledAt: row.disabledAt ? row.disabledAt.toISOString() : null\n\t};\n}\nasync function resolveTriggerAssignments(rows, trigger) {\n\tconst assignments = [];\n\tfor (const row of rows) {\n\t\tif (row.targetKind === \"workflow\" && row.workflowSlug) {\n\t\t\tconst workflow = await selectActiveWorkflowBySlug(row.workflowSlug);\n\t\t\tassignments.push(assignmentFromRow(row, trigger, {\n\t\t\t\tkind: \"workflow\",\n\t\t\t\tid: workflow?.id ?? row.id,\n\t\t\t\tslug: row.workflowSlug,\n\t\t\t\tname: workflow?.name?.trim() || trigger?.name?.trim() || row.workflowSlug\n\t\t\t}));\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.targetKind === \"agent\" && row.agentSlug) {\n\t\t\tconst agent = await selectAgentBySlug(row.agentSlug);\n\t\t\tassignments.push(assignmentFromRow(row, trigger, {\n\t\t\t\tkind: \"agent\",\n\t\t\t\tid: agent?.id ?? row.id,\n\t\t\t\tslug: row.agentSlug,\n\t\t\t\tname: agent?.name?.trim() || trigger?.name?.trim() || row.agentSlug\n\t\t\t}));\n\t\t}\n\t}\n\treturn assignments;\n}\n//#endregion\n//#region src/triggers/workspace.ts\nfunction resourceKey(projectId, slug) {\n\treturn `${projectId}:${slug}`;\n}\nfunction assignmentsForGroup(attachments, trigger, workflows, agents) {\n\tconst assignments = [];\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const row of attachments) {\n\t\tif (row.targetKind === \"workflow\" && row.workflowSlug) {\n\t\t\tconst key = `workflow:${row.workflowSlug}`;\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tconst ref = workflows.get(resourceKey(row.projectId, row.workflowSlug));\n\t\t\tassignments.push({\n\t\t\t\tkind: \"workflow\",\n\t\t\t\tid: ref?.id ?? row.id,\n\t\t\t\tslug: row.workflowSlug,\n\t\t\t\tname: ref?.name?.trim() ?? row.workflowSlug,\n\t\t\t\tattachmentId: row.id,\n\t\t\t\tattachmentSlug: row.slug,\n\t\t\t\tstatus: triggerAttachmentStatusFromRow(row),\n\t\t\t\tdisabledAt: row.disabledAt ? row.disabledAt.toISOString() : null\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.targetKind === \"agent\" && row.agentSlug) {\n\t\t\tconst key = `agent:${row.agentSlug}`;\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tconst ref = agents.get(resourceKey(row.projectId, row.agentSlug));\n\t\t\tassignments.push({\n\t\t\t\tkind: \"agent\",\n\t\t\t\tid: ref?.id ?? row.id,\n\t\t\t\tslug: row.agentSlug,\n\t\t\t\tname: ref?.name?.trim() ?? row.agentSlug,\n\t\t\t\tattachmentId: row.id,\n\t\t\t\tattachmentSlug: row.slug,\n\t\t\t\tstatus: triggerAttachmentStatusFromRow(row),\n\t\t\t\tdisabledAt: row.disabledAt ? row.disabledAt.toISOString() : null\n\t\t\t});\n\t\t}\n\t}\n\treturn assignments;\n}\nfunction buildRecord(trigger, attachments, workflows, agents, lastFiredAt, fireCount) {\n\tconst lastFired = lastFiredAt.get(trigger.id);\n\tconst fires = fireCount.get(trigger.id) ?? 0;\n\tconst name = titleCaseResourceName(trigger.slug, trigger.name);\n\treturn {\n\t\tid: trigger.id,\n\t\tslug: trigger.slug,\n\t\tname,\n\t\tdescription: trigger.description?.trim() || name,\n\t\ttype: trigger.kind,\n\t\tstatus: triggerStatusFromRow(trigger, attachments),\n\t\tprojectId: trigger.projectId,\n\t\tschedule: trigger.schedule,\n\t\tassignments: assignmentsForGroup(attachments, trigger, workflows, agents),\n\t\tlastFiredAt: lastFired ? lastFired.toISOString() : null,\n\t\tfireCount: fires,\n\t\tcreatedAt: trigger.registeredAt.toISOString(),\n\t\tsourcePath: trigger.moduleFile,\n\t\twebhookEndpoint: webhookEndpointFromTriggerConfig(trigger.config ?? null)\n\t};\n}\nasync function buildResourceMaps(projectIds) {\n\tconst [workflowRows, agentRows] = await Promise.all([listActiveWorkflows(projectIds ? { projectIds } : void 0), listActiveAgents(projectIds ? { projectIds } : void 0)]);\n\tconst workflows = /* @__PURE__ */ new Map();\n\tfor (const row of workflowRows) workflows.set(resourceKey(row.projectId, row.slug), {\n\t\tid: row.id,\n\t\tname: row.name\n\t});\n\tconst agents = /* @__PURE__ */ new Map();\n\tfor (const row of agentRows) agents.set(resourceKey(row.projectId, row.slug), {\n\t\tid: row.id,\n\t\tname: row.name\n\t});\n\treturn {\n\t\tworkflows,\n\t\tagents\n\t};\n}\n/** Workspace triggers across the projects the caller can access. */\nasync function listWorkspaceTriggers(projectIds) {\n\tconst triggers = await listActiveTriggersByProjectIds(projectIds);\n\tif (triggers.length === 0) return [];\n\tconst { workflows, agents } = await buildResourceMaps(projectIds);\n\tconst triggerIds = triggers.map((row) => row.id);\n\tconst [attachments, lastFiredAt, fireCount] = await Promise.all([\n\t\tlistAttachmentsByTriggerIds(triggerIds),\n\t\tselectTriggerLastFiredAtByTriggerIds(triggerIds),\n\t\tselectTriggerFireCountByTriggerIds(triggerIds)\n\t]);\n\tconst attachmentsByTriggerId = /* @__PURE__ */ new Map();\n\tfor (const attachment of attachments) {\n\t\tconst existing = attachmentsByTriggerId.get(attachment.triggerId) ?? [];\n\t\texisting.push(attachment);\n\t\tattachmentsByTriggerId.set(attachment.triggerId, existing);\n\t}\n\treturn triggers.map((trigger) => buildRecord(trigger, attachmentsByTriggerId.get(trigger.id) ?? [], workflows, agents, lastFiredAt, fireCount));\n}\nasync function getWorkspaceTrigger(projectId, triggerId) {\n\treturn (await listWorkspaceTriggers([projectId])).find((record) => record.id === triggerId) ?? null;\n}\n/**\n* Run history for a workspace trigger — every fire for the trigger, newest first.\n*/\nasync function listWorkspaceTriggerRunRows(options) {\n\treturn runWithProjectScope(options.projectId, async () => {\n\t\tconst trigger = await selectTriggerById(options.triggerId);\n\t\tif (!trigger || trigger.deletedAt !== null) return null;\n\t\tconst attachments = await listAttachmentsByTriggerIds([trigger.id]);\n\t\tconst result = await listTriggerRunRowsPaginated({\n\t\t\ttriggerIds: [trigger.id],\n\t\t\tlimit: options.limit,\n\t\t\tcursor: options.cursor,\n\t\t\ttriggerType: options.triggerType\n\t\t});\n\t\tif (!attachments.some((row) => row.targetKind === \"agent\" && row.agentSlug)) return result;\n\t\tconst triggerRunIds = result.items.map((item) => item.id);\n\t\tconst [sessionsByTriggerRunId, agents] = await Promise.all([listAgentSessionsBySourceIds({\n\t\t\tsourceKind: \"trigger\",\n\t\t\tsourceIds: triggerRunIds\n\t\t}), listActiveAgents({ projectIds: [options.projectId] })]);\n\t\tconst slugByAgentId = new Map(agents.map((agent) => [agent.id, agent.slug]));\n\t\treturn {\n\t\t\t...result,\n\t\t\titems: result.items.map((item) => {\n\t\t\t\tconst sessions = sessionsByTriggerRunId.get(item.id) ?? [];\n\t\t\t\tif (sessions.length === 0) return item;\n\t\t\t\treturn {\n\t\t\t\t\t...item,\n\t\t\t\t\tagentSessions: sessions.map((session) => ({\n\t\t\t\t\t\tid: session.id,\n\t\t\t\t\t\tagentSlug: slugByAgentId.get(session.agentId) ?? session.agentId\n\t\t\t\t\t}))\n\t\t\t\t};\n\t\t\t})\n\t\t};\n\t});\n}\n//#endregion\n//#region src/triggers/set-attachment-enabled.ts\nasync function syncTriggerScheduleForAttachments(trigger, now) {\n\tif (trigger.kind !== \"cron\" && trigger.kind !== \"poll\") return;\n\tconst executable = await listExecutableAttachmentsByTriggerIds([trigger.id]);\n\tawait setTriggerScheduleEnabled(trigger.slug, executable.length > 0, now);\n}\nasync function setTriggerAttachmentEnabledState(options) {\n\tconst trigger = await selectTriggerById(options.triggerId);\n\tif (!trigger || trigger.deletedAt !== null) return null;\n\tconst attachment = await selectTriggerAttachmentById(options.attachmentId);\n\tif (!attachment || attachment.deletedAt !== null || attachment.triggerId !== trigger.id) return null;\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isTriggerAttachmentExecutable(attachment) === options.enabled) return {\n\t\ttrigger,\n\t\tattachmentId: attachment.id\n\t};\n\tawait setTriggerAttachmentEnabled(attachment.id, options.enabled, now);\n\tawait syncTriggerScheduleForAttachments(trigger, now);\n\treturn {\n\t\ttrigger: await selectTriggerById(trigger.id) ?? trigger,\n\t\tattachmentId: attachment.id\n\t};\n}\n/** Count executable (non-deleted, non-disabled) attachments for a trigger. */\nasync function countExecutableAttachments(triggerId) {\n\treturn (await listExecutableAttachmentsByTriggerIds([triggerId])).length;\n}\n//#endregion\n//#region src/triggers/stored-source-from-row.ts\nfunction storedTriggerSourceFromRow(row) {\n\tconst slug = row.slug;\n\tconst meta = {\n\t\tname: row.name,\n\t\tdescription: row.description\n\t};\n\tif (row.kind === \"webhook\") {\n\t\tconst config = row.config ?? {};\n\t\treturn {\n\t\t\t...meta,\n\t\t\tkind: \"webhook\",\n\t\t\tslug,\n\t\t\tendpoint: config.endpoint,\n\t\t\trequestSchema: config.requestSchema,\n\t\t\t...config.filterSchema ? { filterSchema: config.filterSchema } : {}\n\t\t};\n\t}\n\tif (row.kind === \"cron\") return {\n\t\t...meta,\n\t\tkind: \"cron\",\n\t\tslug,\n\t\tschedule: row.schedule ?? \"\"\n\t};\n\tconst config = row.config ?? {};\n\treturn {\n\t\t...meta,\n\t\tkind: \"poll\",\n\t\tslug,\n\t\tschedule: row.schedule ?? \"\",\n\t\t...config.code ? { code: config.code } : {},\n\t\t...config.id ? { id: config.id } : {}\n\t};\n}\n//#endregion\n//#region src/triggers/ephemeral.ts\n/** Sentinel moduleFile for triggers that exist only in the database. */\nconst EPHEMERAL_TRIGGER_MODULE_FILE = \"__ephemeral__\";\nfunction initialLifecycle(input, existing) {\n\treturn {\n\t\t...input.lifecycle?.maxExecutions !== void 0 ? { maxExecutions: input.lifecycle.maxExecutions } : {},\n\t\t...input.lifecycle?.until !== void 0 ? { until: input.lifecycle.until } : {},\n\t\texecutionCount: existing?.executionCount ?? 0,\n\t\tstatus: input.enabled === false ? \"disabled\" : \"active\"\n\t};\n}\n/** Creates or updates a DB-only trigger for an agent; schedule lives on the trigger row. */\nasync function upsertEphemeralTrigger(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst source = normalizeStoredTriggerSource(input.source);\n\tconst triggerSlug = input.slug;\n\tconst sourceSlug = triggerSlugFromSource(source);\n\tconst existingTrigger = await selectTriggerBySlug(triggerSlug);\n\tconst existingProjectTrigger = await selectTriggerBySlug(sourceSlug);\n\tconst existingAttachment = await selectTriggerAttachmentBySlug(input.slug);\n\tif (existingProjectTrigger && existingProjectTrigger.origin !== \"ephemeral\") throw new Error(`Trigger \"${input.slug}\" is defined in the project and cannot be modified`);\n\tif (existingTrigger && existingTrigger.origin !== \"ephemeral\") throw new Error(`Trigger \"${input.slug}\" is defined in the project and cannot be modified`);\n\tif (existingAttachment && existingAttachment.agentSlug !== input.agentSlug) throw new Error(`Trigger \"${input.slug}\" belongs to another agent`);\n\tconst lifecycle = initialLifecycle(input, existingTrigger?.lifecycle);\n\tconst enabled = lifecycle.status === \"active\";\n\tconst schedule = triggerScheduleFromSource(source);\n\tlet triggerId;\n\tif (existingTrigger) {\n\t\ttriggerId = existingTrigger.id;\n\t\tawait updateTriggerById(existingTrigger.id, {\n\t\t\tname: input.name,\n\t\t\tdescription: input.description,\n\t\t\tmoduleFile: EPHEMERAL_TRIGGER_MODULE_FILE,\n\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\tschedule,\n\t\t\tnextRunAt: source.kind === \"cron\" || source.kind === \"poll\" ? input.nextRunAt ?? existingTrigger.nextRunAt ?? now : null,\n\t\t\tenabled: enabled ? 1 : 0,\n\t\t\tlifecycle,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t} else {\n\t\ttriggerId = crypto.randomUUID();\n\t\tawait insertTrigger({\n\t\t\tid: triggerId,\n\t\t\tslug: triggerSlug,\n\t\t\tkind: source.kind,\n\t\t\tname: input.name,\n\t\t\tdescription: input.description,\n\t\t\tmoduleFile: EPHEMERAL_TRIGGER_MODULE_FILE,\n\t\t\torigin: \"ephemeral\",\n\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\tschedule,\n\t\t\tnextRunAt: source.kind === \"cron\" || source.kind === \"poll\" ? input.nextRunAt ?? now : null,\n\t\t\tenabled: enabled ? 1 : 0,\n\t\t\tlifecycle,\n\t\t\tcreatedBySessionId: input.createdBySessionId ?? null,\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t}\n\tif (source.kind === \"cron\" || source.kind === \"poll\") {\n\t\tif (!input.nextRunAt) throw new Error(`Ephemeral ${source.kind} triggers require nextRunAt`);\n\t}\n\tif (existingAttachment) await updateTriggerAttachmentById(existingAttachment.id, {\n\t\ttargetKind: \"agent\",\n\t\tworkflowSlug: null,\n\t\tagentSlug: input.agentSlug,\n\t\tprompt: input.prompt,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\telse await insertTriggerAttachment({\n\t\tid: crypto.randomUUID(),\n\t\ttriggerId,\n\t\tslug: input.slug,\n\t\ttargetKind: \"agent\",\n\t\tworkflowSlug: null,\n\t\tagentSlug: input.agentSlug,\n\t\tprompt: input.prompt,\n\t\tregisteredAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\tconst row = await selectTriggerAttachmentBySlug(input.slug);\n\tif (!row) throw new Error(`Failed to persist ephemeral trigger \"${input.slug}\"`);\n\treturn row;\n}\n/** Soft-deletes an agent-owned ephemeral trigger and disables its schedule. */\nasync function deleteEphemeralTrigger(options) {\n\tconst row = await selectTriggerAttachmentBySlug(options.slug);\n\tif (!row || row.deletedAt !== null) return false;\n\tconst trigger = await selectTriggerById(row.triggerId);\n\tif (!trigger || trigger.origin !== \"ephemeral\") return false;\n\tif (row.agentSlug !== options.agentSlug) throw new Error(`Trigger \"${options.slug}\" belongs to another agent`);\n\tconst now = /* @__PURE__ */ new Date();\n\tawait updateTriggerAttachmentById(row.id, {\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t});\n\tawait updateTriggerById(trigger.id, {\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t});\n\tawait setTriggerScheduleEnabled(trigger.slug, false, now);\n\treturn true;\n}\n/** Returns true when the trigger may fire now (active status and `until` not passed). */\nfunction isEphemeralTriggerActive(row, now = /* @__PURE__ */ new Date()) {\n\tif (row.origin !== \"ephemeral\" || row.deletedAt !== null) return false;\n\tconst lifecycle = row.lifecycle;\n\tif (!lifecycle) return true;\n\tif (lifecycle.status !== \"active\") return false;\n\tif (lifecycle.until && now >= new Date(lifecycle.until)) return false;\n\treturn true;\n}\n/**\n* Increments executionCount after a fire and completes the trigger when either\n* `maxExecutions` or `until` is met (OR semantics). Row is kept for audit.\n*/\nasync function recordEphemeralTriggerExecution(triggerSlug, now = /* @__PURE__ */ new Date()) {\n\tconst trigger = await selectTriggerBySlug(triggerSlug);\n\tif (!trigger || trigger.origin !== \"ephemeral\") return;\n\tconst lifecycle = trigger.lifecycle ?? {\n\t\texecutionCount: 0,\n\t\tstatus: \"active\"\n\t};\n\tlifecycle.executionCount += 1;\n\tconst maxReached = lifecycle.maxExecutions !== void 0 && lifecycle.executionCount >= lifecycle.maxExecutions;\n\tconst untilPassed = lifecycle.until !== void 0 && now >= new Date(lifecycle.until);\n\tif (lifecycle.status === \"active\" && (maxReached || untilPassed)) {\n\t\tlifecycle.status = \"completed\";\n\t\tawait setTriggerScheduleEnabled(triggerSlug, false, now);\n\t}\n\tawait updateTriggerById(trigger.id, {\n\t\tlifecycle,\n\t\tupdatedAt: now\n\t});\n\treturn lifecycle;\n}\n/** Trigger slugs for active ephemeral scheduled triggers — excluded from project schedule sweeps. */\nasync function selectActiveEphemeralScheduledTriggerSlugs() {\n\treturn (await listActiveEphemeralTriggers()).filter((row) => (row.kind === \"cron\" || row.kind === \"poll\") && isEphemeralTriggerActive(row)).map((row) => row.slug);\n}\n/** @deprecated Use {@link selectActiveEphemeralScheduledTriggerSlugs}. */\nasync function selectActiveEphemeralScheduledAttachmentSlugs() {\n\treturn selectActiveEphemeralScheduledTriggerSlugs();\n}\n/** @deprecated Use {@link selectActiveEphemeralScheduledTriggerSlugs}. */\nasync function selectActiveEphemeralCronAttachmentSlugs() {\n\treturn selectActiveEphemeralScheduledTriggerSlugs();\n}\n//#endregion\n//#region src/triggers/agent-list.ts\nfunction triggerLabel(row, attachment) {\n\treturn row.name?.trim() || row.slug || attachment.slug;\n}\nfunction triggerSchedule(source) {\n\tif (source.kind === \"cron\" || source.kind === \"poll\") return source.schedule;\n\treturn null;\n}\nfunction triggerEndpoint(source) {\n\tif (source.kind === \"webhook\") return source.endpoint;\n\treturn null;\n}\nfunction agentTriggerStatus(row, attachment) {\n\tif (row.origin === \"ephemeral\") {\n\t\tconst lifecycleStatus = row.lifecycle?.status;\n\t\tif (lifecycleStatus === \"disabled\" || lifecycleStatus === \"completed\") return lifecycleStatus;\n\t}\n\tif (triggerAttachmentStatusFromRow(attachment) === \"disabled\") return \"disabled\";\n\treturn row.lifecycle?.status ?? \"active\";\n}\nfunction agentTriggerSummaryFromRows(row, attachment) {\n\tconst source = storedTriggerSourceFromRow(row);\n\treturn {\n\t\tid: attachment.slug,\n\t\tlabel: triggerLabel(row, attachment),\n\t\tname: row.name ?? null,\n\t\tdescription: row.description ?? null,\n\t\ttype: row.kind,\n\t\tschedule: triggerSchedule(source),\n\t\tendpoint: triggerEndpoint(source),\n\t\torigin: row.origin,\n\t\tprompt: attachment.prompt ?? null,\n\t\tstatus: agentTriggerStatus(row, attachment),\n\t\texecutionCount: row.lifecycle?.executionCount ?? 0,\n\t\tuntil: row.lifecycle?.until ?? null,\n\t\tattachmentId: attachment.id,\n\t\tattachmentSlug: attachment.slug\n\t};\n}\nasync function listAgentTriggers(agentSlug) {\n\tconst rows = await selectTriggerAttachmentsByAgentSlug(agentSlug);\n\tconst summaries = [];\n\tfor (const attachment of rows) {\n\t\tconst trigger = await selectTriggerById(attachment.triggerId);\n\t\tif (!trigger) continue;\n\t\tsummaries.push(agentTriggerSummaryFromRows(trigger, attachment));\n\t}\n\treturn summaries;\n}\n//#endregion\n//#region src/gateways/thread-sessions.ts\nasync function getOrCreateGatewayThreadSession(options) {\n\tconst existing = await selectGatewayThreadSessionByThreadId(options.threadId);\n\tif (existing) return existing.sessionId;\n\tconst session = await createSession(options.agentId, options.existingSessionId, runSource(\"gateway\", options.attachmentId));\n\tconst now = /* @__PURE__ */ new Date();\n\tawait upsertGatewayThreadSession({\n\t\tthreadId: options.threadId,\n\t\tagentId: options.agentId,\n\t\tsessionId: session.id,\n\t\tattachmentId: options.attachmentId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn session.id;\n}\n//#endregion\n//#region src/workflows/sync.ts\nfunction workflowMetadata(record) {\n\treturn {\n\t\tname: record.name,\n\t\tdescription: record.description\n\t};\n}\nasync function syncWorkflowRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst bySlug = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectWorkflowBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateWorkflowById(existing.id, {\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\tsubscribable: record.subscribable,\n\t\t\t\t...workflowMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbySlug.set(record.slug, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug,\n\t\t\t\tsubscribable: record.subscribable\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertWorkflow({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\tsubscribable: record.subscribable,\n\t\t\t...workflowMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbySlug.set(record.slug, {\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tsubscribable: record.subscribable\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllWorkflows(now);\n\telse await softDeleteWorkflowsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/workflows/credentials.ts\nasync function getWorkflowSubscription(subscriptionId) {\n\tconst row = await selectWorkflowSubscriptionById(subscriptionId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tworkflowSlug: row.workflowSlug,\n\t\tuserId: row.userId,\n\t\tenabled: Boolean(row.enabled)\n\t};\n}\nasync function listCredentialInstancesForAssignment(options) {\n\tconst tenantScopeId = getServerTenantScopeId();\n\tconst projectId = getProjectScopeId();\n\tconst rows = [];\n\tconst appendScope = async (scopeType, scopeId) => {\n\t\trows.push(...await listCredentialInstancesByScope({\n\t\t\t...options.appSlug ? { appSlug: options.appSlug } : {},\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t};\n\tawait appendScope(\"organization\", tenantScopeId);\n\tawait appendScope(\"project\", projectId);\n\tif (options.userId) await appendScope(\"user\", options.userId);\n\treturn rows;\n}\n//#endregion\n//#region src/workflows/event-log.ts\nfunction createDatabaseEventLog() {\n\treturn {\n\t\tappend(event) {\n\t\t\treturn appendWorkflowEvent(event);\n\t\t},\n\t\tasync listReplay(runId) {\n\t\t\treturn (await listReplayEvents(runId)).map((row) => ({\n\t\t\t\tid: row.id,\n\t\t\t\trunId: row.runId,\n\t\t\t\tseq: row.seq,\n\t\t\t\ttype: row.type,\n\t\t\t\tcorrelationId: row.correlationId,\n\t\t\t\tdata: row.data\n\t\t\t}));\n\t\t}\n\t};\n}\n//#endregion\n//#region src/workflows/hook-store.ts\nfunction hookSummaryFromRow(row) {\n\treturn {\n\t\ttoken: row.token,\n\t\tcorrelationId: row.correlationId,\n\t\tstatus: row.status,\n\t\tcreatedAt: row.createdAt\n\t};\n}\nfunction createDatabaseHookStore() {\n\treturn {\n\t\tcreate(values) {\n\t\t\treturn insertWorkflowHook(values);\n\t\t},\n\t\tasync getByToken(token) {\n\t\t\tconst row = await selectWorkflowHookByToken(token);\n\t\t\tif (!row) return;\n\t\t\treturn {\n\t\t\t\thookId: row.hookId,\n\t\t\t\trunId: row.runId,\n\t\t\t\ttoken: row.token,\n\t\t\t\tcorrelationId: row.correlationId,\n\t\t\t\tstatus: row.status,\n\t\t\t\tschema: row.schema,\n\t\t\t\tpayload: row.payload\n\t\t\t};\n\t\t},\n\t\tasync listByRun(runId, options) {\n\t\t\treturn (await listWorkflowHooksByRun(runId, options)).map(hookSummaryFromRow);\n\t\t},\n\t\tmarkResumed(hookId, payload) {\n\t\t\treturn markWorkflowHookResumed(hookId, payload);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/triggers/run-api.ts\nasync function listTriggerRunsPaginated(options) {\n\tconst attachment = await selectTriggerAttachmentBySlug(options.attachmentSlug);\n\tif (!attachment) return null;\n\tconst result = await listTriggerRunRowsPaginated({\n\t\ttriggerIds: [attachment.triggerId],\n\t\tlimit: options.limit,\n\t\tcursor: options.cursor,\n\t\ttriggerType: options.triggerType\n\t});\n\tconst triggerRunIds = result.items.map((item) => item.id);\n\tif (triggerRunIds.length === 0) return result;\n\tconst [sessionsByTriggerRunId, agents] = await Promise.all([listAgentSessionsBySourceIds({\n\t\tsourceKind: \"trigger\",\n\t\tsourceIds: triggerRunIds\n\t}), listActiveAgents()]);\n\tconst slugByAgentId = new Map(agents.map((agent) => [agent.id, agent.slug]));\n\treturn {\n\t\t...result,\n\t\titems: result.items.map((item) => {\n\t\t\tconst sessions = sessionsByTriggerRunId.get(item.id) ?? [];\n\t\t\tif (sessions.length === 0) return item;\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tagentSessions: sessions.map((session) => ({\n\t\t\t\t\tid: session.id,\n\t\t\t\t\tagentSlug: slugByAgentId.get(session.agentId) ?? session.agentId\n\t\t\t\t}))\n\t\t\t};\n\t\t})\n\t};\n}\nasync function buildTriggerRunDetail(options) {\n\tconst attachment = await selectTriggerAttachmentBySlug(options.attachmentSlug);\n\tif (!attachment) return null;\n\tconst row = await selectTriggerRunForTrigger(attachment.triggerId, options.runId);\n\tif (!row) return null;\n\tconst includeWorkflows = options.include.includes(\"workflows\");\n\tconst includeAgents = options.include.includes(\"agents\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tconst workflowRuns = includeWorkflows ? (await listWorkflowRunsByTriggerRunId(row.id)).map(workflowRunSummaryFromRow) : [];\n\tlet agentSessions = [];\n\tif (includeAgents) {\n\t\tconst sessions = (await listAgentSessionsBySourceIds({\n\t\t\tsourceKind: \"trigger\",\n\t\t\tsourceIds: [row.id]\n\t\t})).get(row.id) ?? [];\n\t\tif (sessions.length > 0) {\n\t\t\tconst agents = await listActiveAgents();\n\t\t\tconst slugByAgentId = new Map(agents.map((agent) => [agent.id, agent.slug]));\n\t\t\tagentSessions = sessions.map((session) => ({\n\t\t\t\tid: session.id,\n\t\t\t\tagentSlug: slugByAgentId.get(session.agentId) ?? session.agentId\n\t\t\t}));\n\t\t}\n\t}\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForTriggerRun(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\trun: triggerRunRecordFromRow(row, attachment.slug),\n\t\tworkflowRuns,\n\t\tagentSessions,\n\t\ttrace\n\t};\n}\n//#endregion\n//#region src/credentials/crypto.ts\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_LENGTH = 12;\nfunction resolveEncryptionKey() {\n\tconst secret = process.env.CREDENTIALS_ENCRYPTION_KEY?.trim();\n\tif (!secret) throw new Error(\"CREDENTIALS_ENCRYPTION_KEY is required\");\n\treturn createHash(\"sha256\").update(secret).digest();\n}\nfunction encryptCredentialPayload(plaintext) {\n\tconst iv = randomBytes(IV_LENGTH);\n\tconst cipher = createCipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tconst encrypted = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n\tconst tag = cipher.getAuthTag();\n\treturn Buffer.concat([\n\t\tiv,\n\t\ttag,\n\t\tencrypted\n\t]).toString(\"base64\");\n}\nfunction decryptCredentialPayload(ciphertext) {\n\tconst buffer = Buffer.from(ciphertext, \"base64\");\n\tconst iv = buffer.subarray(0, IV_LENGTH);\n\tconst tag = buffer.subarray(IV_LENGTH, 28);\n\tconst encrypted = buffer.subarray(28);\n\tconst decipher = createDecipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tdecipher.setAuthTag(tag);\n\treturn Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(\"utf8\");\n}\n//#endregion\n//#region src/credentials/set-instance-value.ts\nasync function setCredentialInstanceValue(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst siblings = await selectCredentialInstancesForScope(options.appSlug, options.scopeType, options.scopeId);\n\tconst isDefault = options.isDefault ?? siblings.length === 0;\n\tconst name = options.name ?? options.label ?? null;\n\tconst slug = options.slug ?? deriveCredentialInstanceSlug({\n\t\tappSlug: options.appSlug,\n\t\tname,\n\t\ttakenSlugs: siblings.map((row) => row.slug)\n\t});\n\tif (isDefault) await clearCredentialInstanceDefaults({\n\t\tappSlug: options.appSlug,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\texceptId: options.id\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: options.id,\n\t\tappSlug: options.appSlug,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault,\n\t\tauthKind: \"api_key\",\n\t\tciphertext: encryptCredentialPayload(JSON.stringify(options.value)),\n\t\tconnectionId: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n//#endregion\n//#region src/oauth/credential-instance.ts\nfunction resolveOAuthInstanceLabel(options) {\n\tconst appName = displayCredentialAppName(options.credentialKey);\n\treturn resolveUniqueCredentialInstanceLabel({\n\t\tbaseLabel: options.userLabel?.trim() || buildCredentialInstanceLabel({\n\t\t\tscopeType: options.scopeType,\n\t\t\tappName,\n\t\t\tprojectName: options.projectName\n\t\t}),\n\t\ttakenLabels: options.rows.filter((row) => !(row.authKind === \"oauth_managed\" && row.connectionId === options.connectionId)).map((row) => row.label),\n\t\tdisambiguator: options.accountLabel?.trim() || options.externalId\n\t});\n}\nasync function reconnectOAuthCredentialInstance(options) {\n\tconst existing = await selectCredentialInstanceById(options.credentialInstanceId);\n\tif (!existing || existing.appSlug !== options.credentialKey || existing.authKind !== \"oauth_managed\") throw new Error(\"Credential not found\");\n\tconst now = /* @__PURE__ */ new Date();\n\tawait upsertCredentialInstance({\n\t\tid: existing.id,\n\t\tappSlug: existing.appSlug,\n\t\tslug: existing.slug,\n\t\tname: existing.name,\n\t\tscopeType: existing.scopeType,\n\t\tscopeId: existing.scopeId,\n\t\tlabel: existing.label,\n\t\tisDefault: Boolean(existing.isDefault),\n\t\tauthKind: \"oauth_managed\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tcreatedAt: existing.createdAt,\n\t\tupdatedAt: now\n\t});\n}\nasync function ensureOAuthInstanceForScope(options) {\n\tconst rows = await selectCredentialInstancesForScope(options.credentialKey, options.scopeType, options.scopeId);\n\tconst oauthRow = rows.find((row) => row.authKind === \"oauth_managed\" && row.connectionId === options.connectionId);\n\tconst now = /* @__PURE__ */ new Date();\n\tif (oauthRow) {\n\t\tconst name = oauthRow.name ?? oauthRow.label ?? resolveOAuthInstanceLabel({\n\t\t\trows,\n\t\t\tconnectionId: options.connectionId,\n\t\t\tcredentialKey: options.credentialKey,\n\t\t\tscopeType: options.scopeType,\n\t\t\tprojectName: options.projectName,\n\t\t\taccountLabel: options.accountLabel,\n\t\t\texternalId: options.externalId,\n\t\t\tuserLabel: options.userLabel\n\t\t});\n\t\tawait upsertCredentialInstance({\n\t\t\tid: oauthRow.id,\n\t\t\tappSlug: options.credentialKey,\n\t\t\tslug: oauthRow.slug,\n\t\t\tname,\n\t\t\tscopeType: options.scopeType,\n\t\t\tscopeId: options.scopeId,\n\t\t\tlabel: name,\n\t\t\tisDefault: Boolean(oauthRow.isDefault),\n\t\t\tauthKind: \"oauth_managed\",\n\t\t\tciphertext: null,\n\t\t\tconnectionId: options.connectionId,\n\t\t\tcreatedAt: oauthRow.createdAt,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn;\n\t}\n\tconst name = resolveOAuthInstanceLabel({\n\t\trows,\n\t\tconnectionId: options.connectionId,\n\t\tcredentialKey: options.credentialKey,\n\t\tscopeType: options.scopeType,\n\t\tprojectName: options.projectName,\n\t\taccountLabel: options.accountLabel,\n\t\texternalId: options.externalId,\n\t\tuserLabel: options.userLabel\n\t});\n\tconst slug = deriveCredentialInstanceSlug({\n\t\tappSlug: options.credentialKey,\n\t\tname,\n\t\ttakenSlugs: rows.map((row) => row.slug)\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: crypto.randomUUID(),\n\t\tappSlug: options.credentialKey,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault: rows.length === 0,\n\t\tauthKind: \"oauth_managed\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n/**\n* Materialize `oauth_managed` credential instances for a connection. Without explicit targets\n* (CLI `keystroke connect`, local server) this keeps the historical behavior of a single\n* org-scoped instance; with targets it fans out one instance per selected scope.\n*\n* Within each scope, instances are keyed by connectionId — the same installation upserts in\n* place; a different external account creates a new labeled row (one default per scope).\n*/\nasync function ensureOAuthCredentialInstance(options) {\n\tconst { credentialKey, connectionId, accountLabel, externalId, userLabel, targets, credentialInstanceId } = options;\n\tif (credentialInstanceId) {\n\t\tconst existing = await selectCredentialInstanceById(credentialInstanceId);\n\t\tif (!existing) throw new Error(\"Credential not found\");\n\t\tconst reconnect = () => reconnectOAuthCredentialInstance({\n\t\t\tcredentialInstanceId,\n\t\t\tcredentialKey,\n\t\t\tconnectionId\n\t\t});\n\t\tif (existing.scopeType === \"project\" && existing.scopeId) {\n\t\t\tawait runWithProjectScope(existing.scopeId, reconnect);\n\t\t\treturn;\n\t\t}\n\t\tawait reconnect();\n\t\treturn;\n\t}\n\tconst hasTargets = Boolean(targets && ((targets.projectIds?.length ?? 0) > 0 || targets.organization || targets.userId));\n\tconst scopeOptions = {\n\t\tcredentialKey,\n\t\tconnectionId,\n\t\taccountLabel,\n\t\texternalId,\n\t\tuserLabel\n\t};\n\tif (!hasTargets || targets?.organization) await ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"organization\",\n\t\tscopeId: getServerTenantScopeId()\n\t});\n\tfor (const projectId of targets?.projectIds ?? []) await runWithProjectScope(projectId, () => ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"project\",\n\t\tscopeId: projectId,\n\t\tprojectName: targets?.projectNamesById?.[projectId]\n\t}));\n\tif (targets?.userId) await ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"user\",\n\t\tscopeId: targets.userId\n\t});\n}\n//#endregion\n//#region src/oauth/keystroke-credential-instance.ts\nfunction resolveKeystrokeInstanceLabel(options) {\n\tconst appName = displayCredentialAppName(options.credentialKey);\n\treturn resolveUniqueCredentialInstanceLabel({\n\t\tbaseLabel: options.accountLabel?.trim() || buildCredentialInstanceLabel({\n\t\t\tscopeType: options.scopeType,\n\t\t\tappName,\n\t\t\tprojectName: options.projectName\n\t\t}),\n\t\ttakenLabels: options.rows.filter((row) => !(row.authKind === \"keystroke\" && row.connectionId === options.connectionId)).map((row) => row.label)\n\t});\n}\nasync function reconnectKeystrokeCredentialInstance(options) {\n\tconst existing = await selectCredentialInstanceById(options.credentialInstanceId);\n\tif (!existing || existing.appSlug !== options.credentialKey || existing.authKind !== \"keystroke\") throw new Error(\"Credential not found\");\n\tconst now = /* @__PURE__ */ new Date();\n\tawait upsertCredentialInstance({\n\t\tid: existing.id,\n\t\tappSlug: existing.appSlug,\n\t\tslug: existing.slug,\n\t\tname: existing.name,\n\t\tscopeType: existing.scopeType,\n\t\tscopeId: existing.scopeId,\n\t\tlabel: existing.label,\n\t\tisDefault: Boolean(existing.isDefault),\n\t\tauthKind: \"keystroke\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tsharedConnectionId: options.sharedConnectionId,\n\t\tgrantedScopes: options.grantedScopes ?? existing.grantedScopes ?? null,\n\t\tcreatedAt: existing.createdAt,\n\t\tupdatedAt: now\n\t});\n}\nasync function ensureKeystrokeInstanceForScope(options) {\n\tconst rows = await selectCredentialInstancesForScope(options.credentialKey, options.scopeType, options.scopeId);\n\tconst existingByConnection = rows.find((row) => row.authKind === \"keystroke\" && row.connectionId === options.connectionId);\n\tconst now = /* @__PURE__ */ new Date();\n\tconst name = existingByConnection?.name ?? existingByConnection?.label ?? resolveKeystrokeInstanceLabel({\n\t\trows,\n\t\tconnectionId: options.connectionId,\n\t\tcredentialKey: options.credentialKey,\n\t\tscopeType: options.scopeType,\n\t\tprojectName: options.projectName,\n\t\taccountLabel: options.accountLabel\n\t});\n\tconst existing = existingByConnection;\n\tconst slug = existing?.slug ?? deriveCredentialInstanceSlug({\n\t\tappSlug: options.credentialKey,\n\t\tname,\n\t\ttakenSlugs: rows.map((row) => row.slug)\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: existing?.id ?? crypto.randomUUID(),\n\t\tappSlug: options.credentialKey,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault: existing ? Boolean(existing.isDefault) : rows.length === 0,\n\t\tauthKind: \"keystroke\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tsharedConnectionId: options.sharedConnectionId,\n\t\tgrantedScopes: options.grantedScopes ?? existing?.grantedScopes ?? null,\n\t\tcreatedAt: existing?.createdAt ?? now,\n\t\tupdatedAt: now\n\t});\n}\nasync function ensureKeystrokeCredentialInstance(options) {\n\tif (options.credentialInstanceId) {\n\t\tconst existing = await selectCredentialInstanceById(options.credentialInstanceId);\n\t\tif (!existing) throw new Error(\"Credential not found\");\n\t\tconst reconnect = () => reconnectKeystrokeCredentialInstance({\n\t\t\tcredentialInstanceId: options.credentialInstanceId,\n\t\t\tcredentialKey: options.credentialKey,\n\t\t\tconnectionId: options.connectionId,\n\t\t\tsharedConnectionId: options.sharedConnectionId,\n\t\t\tgrantedScopes: options.grantedScopes\n\t\t});\n\t\tif (existing.scopeType === \"project\" && existing.scopeId) {\n\t\t\tawait runWithProjectScope(existing.scopeId, reconnect);\n\t\t\treturn;\n\t\t}\n\t\tawait reconnect();\n\t\treturn;\n\t}\n\tconst { scopeType, scopeId, ...scopeOptions } = options;\n\tif (scopeType === \"project\") {\n\t\tawait runWithProjectScope(scopeId, () => ensureKeystrokeInstanceForScope({\n\t\t\t...scopeOptions,\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t\treturn;\n\t}\n\tawait ensureKeystrokeInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType,\n\t\tscopeId\n\t});\n}\n//#endregion\n//#region src/scheduler/jobs.ts\nconst DEFAULT_MAX_ATTEMPTS = 3;\nasync function enqueueJob(input) {\n\tconst id = crypto.randomUUID();\n\tawait insertJob({\n\t\tid,\n\t\tkind: input.kind,\n\t\ttargetId: input.targetId,\n\t\trunId: input.runId,\n\t\ttrigger: input.trigger,\n\t\tpayload: input.payload ?? null,\n\t\tstatus: \"pending\",\n\t\tscheduledAt: input.scheduledAt ?? /* @__PURE__ */ new Date(),\n\t\tattempt: input.attempt ?? 1,\n\t\tmaxAttempts: input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null,\n\t\tcompletedAt: null,\n\t\terror: null\n\t});\n\treturn id;\n}\nasync function claimNextJob(workerId) {\n\tconst row = await claimNextJobRow(workerId);\n\tif (!row) return;\n\tawait markJobRunning(row.id);\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttargetId: row.targetId,\n\t\trunId: row.runId,\n\t\ttrigger: row.trigger,\n\t\tpayload: row.payload ?? {},\n\t\tattempt: row.attempt,\n\t\tmaxAttempts: row.maxAttempts,\n\t\tscheduledAt: row.scheduledAt\n\t};\n}\nasync function markJobComplete(jobId) {\n\tawait completeJobRow(jobId, /* @__PURE__ */ new Date());\n}\nasync function markJobFailed(jobId, error) {\n\tawait failJobRow(jobId, error instanceof Error ? {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t} : { message: String(error) }, /* @__PURE__ */ new Date());\n}\nasync function scheduleJobRetry(jobId, attempt, delayMs) {\n\tawait resetJobForRetry(jobId, new Date(Date.now() + delayMs), attempt);\n}\nasync function getJobByRunId(runId) {\n\tconst row = await selectJobByRunId(runId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttargetId: row.targetId,\n\t\trunId: row.runId,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\tpayload: row.payload ?? {},\n\t\tattempt: row.attempt,\n\t\tmaxAttempts: row.maxAttempts,\n\t\tscheduledAt: row.scheduledAt,\n\t\terror: row.error ?? null\n\t};\n}\n//#endregion\nexport { DEFAULT_DATABASE_URL, DEFAULT_PROJECT_ID, EPHEMERAL_TRIGGER_MODULE_FILE, GatewayChannelConflictError, MESSAGE_EVENT_TYPE, acquireProjectDatabasePool, adaptPgMigrationsForSearchPath, addAgentSessionDuration, appendEvent, assertPgIdent, buildAgentSessionChatState, buildAgentSessionDetail, buildHistoryAgentSessionDetail, buildHistoryWorkflowRunDetail, buildPostgresUrl, buildTriggerRunDetail, buildWorkflowRunDetail, cancelAgentSession, cancelWorkflowRun, claimDueTriggers, claimDueTriggersForOrg, claimNextJob, clearAgentSessionCancellation, clearCredentialInstanceDefaults, clearLiveMessage, closeAllProjectDatabasePools, closeDatabase, completeWorkflowRun, countExecutableAttachments, countMessageEvents, createAgentAttachmentExecution, createAttachmentExecution, createConnection, createDatabaseEventLog, createDatabaseHookStore, createDatabaseTracingSink, createOrgScopedHandle, createPendingAttachmentExecution, createPendingWorkflowRun, createPgConnection, createPostgresCancelChannel, createPublicScopedHandle, createPublicScopedPool, createSession, createSqliteConnection, createWorkflowRun, decryptCredentialPayload, deleteCredentialAssignmentById, deleteCredentialInstanceById, deleteEphemeralTrigger, deleteWorkflowSubscriptionById, disableAllTriggerSchedules, disableTriggerSchedulesNotInSlugs, encryptCredentialPayload, enqueueJob, ensureKeystrokeCredentialInstance, ensureOAuthCredentialInstance, failAgentSession, failWorkflowRun, finalizeCanceledWorkflowRun, findHistoryRunCore, gatewayAttachmentKeyForChannel, getActiveGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByTeamAndChannel, getAgentByRoute, getBoundProjectScopeId, getDatabaseHandle, getGatewayAttachmentBySlug, getJobByRunId, getOrCreateGatewayThreadSession, getProjectScopeId, getServerTenantScopeId, getSession, getSessionLiveMessage, getTraceForAgentSession, getTraceForTriggerRun, getTraceForWorkflowRun, getTriggerAttachmentBySlug, getTriggerRunForAgentSession, getWorkflowSubscription, getWorkspaceTrigger, inferDialect, initDatabase, insertWorkflowSubscription, isDatabaseInitialized, isEphemeralTriggerActive, listActiveAgents, listActiveGatewayAttachments, listActiveGatewayAttachmentsByAgentSlug, listActiveGatewayAttachmentsByPlatform, listActiveOrgGatewayBindingsByPlatform, listActiveSkills, listActiveTriggerAttachments, listActiveWorkflows, listAgentSessionsPaginated, listAgentTriggers, listAllCredentialInstances, listAttachmentsByTriggerIds, listCredentialAssignmentsByTarget, listCredentialInstancesByConnectionId, listCredentialInstancesByScope, listCredentialInstancesForAssignment, listDistinctAssignmentConsumerIds, listEnabledScheduledTriggers, listEnabledWorkflowSubscriptionsByWorkflowSlug, listExecutableAttachmentsByTriggerIds, listHistoryRuns, listMessageEvents, listRecentResourceActivity, listRecentWorkflowStepConsumers, listReplayEvents, listSessionEvents, listStepCompletedEvents, listTriggerRunsPaginated, listTriggersByIds, listWorkflowRunsByWorkflowSlug, listWorkflowRunsPaginated, listWorkflowSubscriptionsByWorkflowSlug, listWorkspaceTriggerRunRows, listWorkspaceTriggers, loadMigrations, markAttachmentExecutionRunning, markJobComplete, markJobFailed, markWorkflowRunRunning, markWorkflowRunSleeping, markWorkflowRunWaitingHook, migratePgDatabase, nextSeq, normalizeStoredTriggerSource, parsePostgresUrl, primarySearchPathSchema, qualifyConnectionUser, quotePgIdent, recordEphemeralTriggerExecution, recordLlmUsageFromAssistantMessage, recordTriggerFire, recordWorkflowLlmUsage, requeueExpiredLeases, resolveAgentProjectId, resolveDatabaseUrlFromEnv, resolveMigrationsFolder, resolveMigrationsSchema, resolvePostgresConfigFromEnv, resolvePostgresUrlFromEnv, resolveProjectDatabaseUrlFromEnv, resolveRunSourceFromTraceContext, resolveSearchPath, resolveSqlitePath, resolveTriggerAssignments, resolveWorkflowRunProjectId, runMigrations, runSource, runWithProjectDatabase, runWithProjectScope, runWithTenantScope, scheduleJobRetry, selectActiveAgentById, selectActiveAgentsByIds, selectActiveEphemeralCronAttachmentSlugs, selectActiveEphemeralScheduledAttachmentSlugs, selectActiveEphemeralScheduledTriggerSlugs, selectActiveSkillById, selectActiveSkillsByIds, selectActiveWorkflowById, selectActiveWorkflowBySlug, selectActiveWorkflowsByIds, selectAgentBySlug, selectAgentLastRunAtByIds, selectAgentSessionById, selectCredentialAssignmentById, selectCredentialInstanceById, selectCredentialInstancesForScope, selectDisabledAttachmentSlugs, selectEphemeralTriggerAttachments, selectEphemeralTriggerAttachmentsByAgentSlug, selectGatewayThreadSessionByThreadId, selectProjectResourceCounts, selectTriggerAttachmentsByAgentSlug, selectTriggerById, selectTriggerBySlug, selectWebhookTriggerAttachments, selectWebhookTriggers, selectWorkflowCanvasAnnotations, selectWorkflowLastRunAtByIds, selectWorkflowOverview, selectWorkflowRunById, selectWorkflowRunForWorkflow, selectWorkflowRunInputValues, selectWorkflowSubscriptionById, selectWorkflowSubscriptionByWorkflowAndUser, setCredentialInstanceValue, setSessionLiveMessage, setSessionTitle, setTriggerAttachmentEnabled, setTriggerAttachmentEnabledState, setTriggerOverviewGenerating, setTriggerScheduleEnabled, setWorkflowCanvasAnnotationsGenerating, setWorkflowOverviewGenerating, softDeleteGatewayAttachmentByChannel, softDeleteGatewayAttachmentsForAgentPlatformTeam, sourceFromSpan, storedTriggerSourceFromRow, storedTriggerSourceFromTrigger, storedTriggerSourceSlug, syncAgentRegistry, syncSkillRegistry, syncTriggerAttachmentRegistry, syncWorkflowRegistry, touchCredentialInstanceLastUsed, touchResourceActivity, touchSession, triggerAttachmentStatusFromRow, triggerScheduleFromSource, triggerSourceGroupKeyFromSource, triggerStatusFromRow, updateTriggerOverview, updateWorkflowCanvasAnnotations, updateWorkflowOverview, updateWorkflowRunInputValues, updateWorkflowSubscriptionById, upsertCredentialAssignment, upsertCredentialInstance, upsertEphemeralTrigger, upsertGatewayAttachmentByChannel, upsertTriggerScheduleFields };\n\n//# sourceMappingURL=index.mjs.map","var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n  for (var name22 in all)\n    __defProp(target, name22, { get: all[name22], enumerable: true });\n};\n\n// src/index.ts\nimport { createGateway, gateway as gateway2 } from \"@ai-sdk/gateway\";\nimport {\n  asSchema as asSchema7,\n  createIdGenerator as createIdGenerator9,\n  dynamicTool,\n  generateId,\n  jsonSchema,\n  parseJsonEventStream as parseJsonEventStream3,\n  tool,\n  zodSchema as zodSchema3\n} from \"@ai-sdk/provider-utils\";\n\n// src/agent/tool-loop-agent.ts\nimport {\n  validateTypes as validateTypes3,\n  withUserAgentSuffix as withUserAgentSuffix3\n} from \"@ai-sdk/provider-utils\";\n\n// src/generate-text/generate-text.ts\nimport {\n  asArray as asArray5,\n  createIdGenerator,\n  getErrorMessage as getErrorMessage5,\n  withUserAgentSuffix as withUserAgentSuffix2\n} from \"@ai-sdk/provider-utils\";\n\n// src/error/index.ts\nimport {\n  AISDKError as AISDKError22,\n  APICallError,\n  EmptyResponseBodyError,\n  InvalidPromptError,\n  InvalidResponseDataError,\n  JSONParseError,\n  LoadAPIKeyError,\n  LoadSettingError,\n  NoContentGeneratedError,\n  NoSuchModelError,\n  NoSuchProviderReferenceError,\n  TooManyEmbeddingValuesForCallError,\n  TypeValidationError,\n  UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\n\n// src/error/invalid-argument-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_InvalidArgumentError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a;\nvar InvalidArgumentError = class extends AISDKError {\n  constructor({\n    parameter,\n    value,\n    message\n  }) {\n    super({\n      name,\n      message: `Invalid argument for parameter ${parameter}: ${message}`\n    });\n    this[_a] = true;\n    this.parameter = parameter;\n    this.value = value;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker);\n  }\n};\n_a = symbol;\n\n// src/error/invalid-stream-part-error.ts\nimport { AISDKError as AISDKError2 } from \"@ai-sdk/provider\";\nvar name2 = \"AI_InvalidStreamPartError\";\nvar marker2 = `vercel.ai.error.${name2}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2;\nvar InvalidStreamPartError = class extends AISDKError2 {\n  constructor({\n    chunk,\n    message\n  }) {\n    super({ name: name2, message });\n    this[_a2] = true;\n    this.chunk = chunk;\n  }\n  static isInstance(error) {\n    return AISDKError2.hasMarker(error, marker2);\n  }\n};\n_a2 = symbol2;\n\n// src/error/invalid-tool-approval-error.ts\nimport { AISDKError as AISDKError3 } from \"@ai-sdk/provider\";\nvar name3 = \"AI_InvalidToolApprovalError\";\nvar marker3 = `vercel.ai.error.${name3}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3;\nvar InvalidToolApprovalError = class extends AISDKError3 {\n  constructor({ approvalId }) {\n    super({\n      name: name3,\n      message: `Tool approval response references unknown approvalId: \"${approvalId}\". No matching tool-approval-request found in message history.`\n    });\n    this[_a3] = true;\n    this.approvalId = approvalId;\n  }\n  static isInstance(error) {\n    return AISDKError3.hasMarker(error, marker3);\n  }\n};\n_a3 = symbol3;\n\n// src/error/invalid-tool-approval-signature-error.ts\nimport { AISDKError as AISDKError4 } from \"@ai-sdk/provider\";\nvar name4 = \"AI_InvalidToolApprovalSignatureError\";\nvar marker4 = `vercel.ai.error.${name4}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4;\nvar InvalidToolApprovalSignatureError = class extends AISDKError4 {\n  constructor({\n    approvalId,\n    toolCallId,\n    reason\n  }) {\n    super({\n      name: name4,\n      message: `Tool approval signature verification failed for approval \"${approvalId}\" (tool call \"${toolCallId}\"): ${reason}`\n    });\n    this[_a4] = true;\n    this.approvalId = approvalId;\n    this.toolCallId = toolCallId;\n  }\n  static isInstance(error) {\n    return AISDKError4.hasMarker(error, marker4);\n  }\n};\n_a4 = symbol4;\n\n// src/error/invalid-tool-input-error.ts\nimport { AISDKError as AISDKError5, getErrorMessage } from \"@ai-sdk/provider\";\nvar name5 = \"AI_InvalidToolInputError\";\nvar marker5 = `vercel.ai.error.${name5}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5;\nvar InvalidToolInputError = class extends AISDKError5 {\n  constructor({\n    toolInput,\n    toolName,\n    cause,\n    message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}`\n  }) {\n    super({ name: name5, message, cause });\n    this[_a5] = true;\n    this.toolInput = toolInput;\n    this.toolName = toolName;\n  }\n  static isInstance(error) {\n    return AISDKError5.hasMarker(error, marker5);\n  }\n};\n_a5 = symbol5;\n\n// src/error/tool-call-not-found-for-approval-error.ts\nimport { AISDKError as AISDKError6 } from \"@ai-sdk/provider\";\nvar name6 = \"AI_ToolCallNotFoundForApprovalError\";\nvar marker6 = `vercel.ai.error.${name6}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6;\nvar ToolCallNotFoundForApprovalError = class extends AISDKError6 {\n  constructor({\n    toolCallId,\n    approvalId\n  }) {\n    super({\n      name: name6,\n      message: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`\n    });\n    this[_a6] = true;\n    this.toolCallId = toolCallId;\n    this.approvalId = approvalId;\n  }\n  static isInstance(error) {\n    return AISDKError6.hasMarker(error, marker6);\n  }\n};\n_a6 = symbol6;\n\n// src/error/missing-tool-result-error.ts\nimport { AISDKError as AISDKError7 } from \"@ai-sdk/provider\";\nvar name7 = \"AI_MissingToolResultsError\";\nvar marker7 = `vercel.ai.error.${name7}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7;\nvar MissingToolResultsError = class extends AISDKError7 {\n  constructor({ toolCallIds }) {\n    super({\n      name: name7,\n      message: `Tool result${toolCallIds.length > 1 ? \"s are\" : \" is\"} missing for tool call${toolCallIds.length > 1 ? \"s\" : \"\"} ${toolCallIds.join(\n        \", \"\n      )}.`\n    });\n    this[_a7] = true;\n    this.toolCallIds = toolCallIds;\n  }\n  static isInstance(error) {\n    return AISDKError7.hasMarker(error, marker7);\n  }\n};\n_a7 = symbol7;\n\n// src/error/no-image-generated-error.ts\nimport { AISDKError as AISDKError8 } from \"@ai-sdk/provider\";\nvar name8 = \"AI_NoImageGeneratedError\";\nvar marker8 = `vercel.ai.error.${name8}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8;\nvar NoImageGeneratedError = class extends AISDKError8 {\n  constructor({\n    message = \"No image generated.\",\n    cause,\n    responses\n  }) {\n    super({ name: name8, message, cause });\n    this[_a8] = true;\n    this.responses = responses;\n  }\n  static isInstance(error) {\n    return AISDKError8.hasMarker(error, marker8);\n  }\n};\n_a8 = symbol8;\n\n// src/error/no-object-generated-error.ts\nimport { AISDKError as AISDKError9 } from \"@ai-sdk/provider\";\nvar name9 = \"AI_NoObjectGeneratedError\";\nvar marker9 = `vercel.ai.error.${name9}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9;\nvar NoObjectGeneratedError = class extends AISDKError9 {\n  constructor({\n    message = \"No object generated.\",\n    cause,\n    text: text2,\n    response,\n    usage,\n    finishReason\n  }) {\n    super({ name: name9, message, cause });\n    this[_a9] = true;\n    this.text = text2;\n    this.response = response;\n    this.usage = usage;\n    this.finishReason = finishReason;\n  }\n  static isInstance(error) {\n    return AISDKError9.hasMarker(error, marker9);\n  }\n};\n_a9 = symbol9;\n\n// src/error/no-output-generated-error.ts\nimport { AISDKError as AISDKError10 } from \"@ai-sdk/provider\";\nvar name10 = \"AI_NoOutputGeneratedError\";\nvar marker10 = `vercel.ai.error.${name10}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10;\nvar NoOutputGeneratedError = class extends AISDKError10 {\n  // used in isInstance\n  constructor({\n    message = \"No output generated.\",\n    cause\n  } = {}) {\n    super({ name: name10, message, cause });\n    this[_a10] = true;\n  }\n  static isInstance(error) {\n    return AISDKError10.hasMarker(error, marker10);\n  }\n};\n_a10 = symbol10;\n\n// src/error/no-speech-generated-error.ts\nimport { AISDKError as AISDKError11 } from \"@ai-sdk/provider\";\nvar name11 = \"AI_NoSpeechGeneratedError\";\nvar marker11 = `vercel.ai.error.${name11}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11;\nvar NoSpeechGeneratedError = class extends AISDKError11 {\n  constructor(options) {\n    super({\n      name: name11,\n      message: \"No speech audio generated.\"\n    });\n    this[_a11] = true;\n    this.responses = options.responses;\n  }\n  static isInstance(error) {\n    return AISDKError11.hasMarker(error, marker11);\n  }\n};\n_a11 = symbol11;\n\n// src/error/no-transcript-generated-error.ts\nimport { AISDKError as AISDKError12 } from \"@ai-sdk/provider\";\nvar name12 = \"AI_NoTranscriptGeneratedError\";\nvar marker12 = `vercel.ai.error.${name12}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12;\nvar NoTranscriptGeneratedError = class extends AISDKError12 {\n  constructor(options) {\n    super({\n      name: name12,\n      message: \"No transcript generated.\"\n    });\n    this[_a12] = true;\n    this.responses = options.responses;\n  }\n  static isInstance(error) {\n    return AISDKError12.hasMarker(error, marker12);\n  }\n};\n_a12 = symbol12;\n\n// src/error/no-video-generated-error.ts\nimport { AISDKError as AISDKError13 } from \"@ai-sdk/provider\";\nvar name13 = \"AI_NoVideoGeneratedError\";\nvar marker13 = `vercel.ai.error.${name13}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13;\nvar NoVideoGeneratedError = class extends AISDKError13 {\n  constructor({\n    message = \"No video generated.\",\n    cause,\n    responses\n  }) {\n    super({ name: name13, message, cause });\n    this[_a13] = true;\n    this.responses = responses;\n  }\n  static isInstance(error) {\n    return AISDKError13.hasMarker(error, marker13);\n  }\n  /**\n   * @deprecated use `isInstance` instead\n   */\n  static isNoVideoGeneratedError(error) {\n    return error instanceof Error && error.name === name13 && typeof error.responses !== \"undefined\" ? true : false;\n  }\n  /**\n   * @deprecated Do not use this method. It will be removed in the next major version.\n   */\n  toJSON() {\n    return {\n      name: this.name,\n      message: this.message,\n      stack: this.stack,\n      cause: this.cause,\n      responses: this.responses\n    };\n  }\n};\n_a13 = symbol13;\n\n// src/error/no-such-tool-error.ts\nimport { AISDKError as AISDKError14 } from \"@ai-sdk/provider\";\nvar name14 = \"AI_NoSuchToolError\";\nvar marker14 = `vercel.ai.error.${name14}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14;\nvar NoSuchToolError = class extends AISDKError14 {\n  constructor({\n    toolName,\n    availableTools = void 0,\n    message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? \"No tools are available.\" : `Available tools: ${availableTools.join(\", \")}.`}`\n  }) {\n    super({ name: name14, message });\n    this[_a14] = true;\n    this.toolName = toolName;\n    this.availableTools = availableTools;\n  }\n  static isInstance(error) {\n    return AISDKError14.hasMarker(error, marker14);\n  }\n};\n_a14 = symbol14;\n\n// src/error/tool-call-repair-error.ts\nimport { AISDKError as AISDKError15, getErrorMessage as getErrorMessage2 } from \"@ai-sdk/provider\";\nvar name15 = \"AI_ToolCallRepairError\";\nvar marker15 = `vercel.ai.error.${name15}`;\nvar symbol15 = Symbol.for(marker15);\nvar _a15;\nvar ToolCallRepairError = class extends AISDKError15 {\n  constructor({\n    cause,\n    originalError,\n    message = `Error repairing tool call: ${getErrorMessage2(cause)}`\n  }) {\n    super({ name: name15, message, cause });\n    this[_a15] = true;\n    this.originalError = originalError;\n  }\n  static isInstance(error) {\n    return AISDKError15.hasMarker(error, marker15);\n  }\n};\n_a15 = symbol15;\n\n// src/error/unsupported-model-version-error.ts\nimport { AISDKError as AISDKError16 } from \"@ai-sdk/provider\";\nvar UnsupportedModelVersionError = class extends AISDKError16 {\n  constructor(options) {\n    super({\n      name: \"AI_UnsupportedModelVersionError\",\n      message: `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". AI SDK 5 only supports models that implement specification version \"v2\".`\n    });\n    this.version = options.version;\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n  }\n};\n\n// src/error/ui-message-stream-error.ts\nimport { AISDKError as AISDKError17 } from \"@ai-sdk/provider\";\nvar name16 = \"AI_UIMessageStreamError\";\nvar marker16 = `vercel.ai.error.${name16}`;\nvar symbol16 = Symbol.for(marker16);\nvar _a16;\nvar UIMessageStreamError = class extends AISDKError17 {\n  constructor({\n    chunkType,\n    chunkId,\n    message\n  }) {\n    super({ name: name16, message });\n    this[_a16] = true;\n    this.chunkType = chunkType;\n    this.chunkId = chunkId;\n  }\n  static isInstance(error) {\n    return AISDKError17.hasMarker(error, marker16);\n  }\n};\n_a16 = symbol16;\n\n// src/prompt/invalid-data-content-error.ts\nimport { AISDKError as AISDKError18 } from \"@ai-sdk/provider\";\nvar name17 = \"AI_InvalidDataContentError\";\nvar marker17 = `vercel.ai.error.${name17}`;\nvar symbol17 = Symbol.for(marker17);\nvar _a17;\nvar InvalidDataContentError = class extends AISDKError18 {\n  constructor({\n    content,\n    cause,\n    message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`\n  }) {\n    super({ name: name17, message, cause });\n    this[_a17] = true;\n    this.content = content;\n  }\n  static isInstance(error) {\n    return AISDKError18.hasMarker(error, marker17);\n  }\n};\n_a17 = symbol17;\n\n// src/prompt/invalid-message-role-error.ts\nimport { AISDKError as AISDKError19 } from \"@ai-sdk/provider\";\nvar name18 = \"AI_InvalidMessageRoleError\";\nvar marker18 = `vercel.ai.error.${name18}`;\nvar symbol18 = Symbol.for(marker18);\nvar _a18;\nvar InvalidMessageRoleError = class extends AISDKError19 {\n  constructor({\n    role,\n    message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`\n  }) {\n    super({ name: name18, message });\n    this[_a18] = true;\n    this.role = role;\n  }\n  static isInstance(error) {\n    return AISDKError19.hasMarker(error, marker18);\n  }\n};\n_a18 = symbol18;\n\n// src/prompt/message-conversion-error.ts\nimport { AISDKError as AISDKError20 } from \"@ai-sdk/provider\";\nvar name19 = \"AI_MessageConversionError\";\nvar marker19 = `vercel.ai.error.${name19}`;\nvar symbol19 = Symbol.for(marker19);\nvar _a19;\nvar MessageConversionError = class extends AISDKError20 {\n  constructor({\n    originalMessage,\n    message\n  }) {\n    super({ name: name19, message });\n    this[_a19] = true;\n    this.originalMessage = originalMessage;\n  }\n  static isInstance(error) {\n    return AISDKError20.hasMarker(error, marker19);\n  }\n};\n_a19 = symbol19;\n\n// src/error/index.ts\nimport { DownloadError } from \"@ai-sdk/provider-utils\";\n\n// src/util/retry-error.ts\nimport { AISDKError as AISDKError21 } from \"@ai-sdk/provider\";\nvar name20 = \"AI_RetryError\";\nvar marker20 = `vercel.ai.error.${name20}`;\nvar symbol20 = Symbol.for(marker20);\nvar _a20;\nvar RetryError = class extends AISDKError21 {\n  constructor({\n    message,\n    reason,\n    errors\n  }) {\n    super({ name: name20, message });\n    this[_a20] = true;\n    this.reason = reason;\n    this.errors = errors;\n    this.lastError = errors[errors.length - 1];\n  }\n  static isInstance(error) {\n    return AISDKError21.hasMarker(error, marker20);\n  }\n};\n_a20 = symbol20;\n\n// src/logger/log-warnings.ts\nfunction formatWarning({\n  warning,\n  provider,\n  model\n}) {\n  const scope = provider != null && model != null ? ` (${provider} / ${model})` : \"\";\n  const prefix = `AI SDK Warning${scope}:`;\n  switch (warning.type) {\n    case \"unsupported\": {\n      let message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n      if (warning.details) {\n        message += ` ${warning.details}`;\n      }\n      return message;\n    }\n    case \"compatibility\": {\n      let message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n      if (warning.details) {\n        message += ` ${warning.details}`;\n      }\n      return message;\n    }\n    case \"deprecated\": {\n      return `${prefix} Deprecated: \"${warning.setting}\". ${warning.message}`;\n    }\n    case \"other\": {\n      return `${prefix} ${warning.message}`;\n    }\n    default: {\n      return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n    }\n  }\n}\nvar FIRST_WARNING_INFO_MESSAGE = \"AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.\";\nvar hasLoggedBefore = false;\nvar logWarnings = (options) => {\n  if (options.warnings.length === 0) {\n    return;\n  }\n  const logger = globalThis.AI_SDK_LOG_WARNINGS;\n  if (logger === false) {\n    return;\n  }\n  if (typeof logger === \"function\") {\n    logger(options);\n    return;\n  }\n  if (!hasLoggedBefore) {\n    hasLoggedBefore = true;\n    console.info(FIRST_WARNING_INFO_MESSAGE);\n  }\n  for (const warning of options.warnings) {\n    const message = formatWarning({\n      warning,\n      provider: options.provider,\n      model: options.model\n    });\n    if (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") {\n      process.emitWarning(message, {\n        type: warning.type === \"deprecated\" ? \"DeprecationWarning\" : \"Warning\"\n      });\n    } else {\n      console.warn(message);\n    }\n  }\n};\n\n// src/model/resolve-model.ts\nimport { gateway } from \"@ai-sdk/gateway\";\n\n// src/util/log-v2-compatibility-warning.ts\nfunction logV2CompatibilityWarning({\n  provider,\n  modelId\n}) {\n  logWarnings({\n    warnings: [\n      {\n        type: \"compatibility\",\n        feature: \"specificationVersion\",\n        details: `Using v2 specification compatibility mode. Some features may not be available.`\n      }\n    ],\n    provider,\n    model: modelId\n  });\n}\n\n// src/model/as-embedding-model-v3.ts\nfunction asEmbeddingModelV3(model) {\n  if (model.specificationVersion === \"v3\") {\n    return model;\n  }\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId\n  });\n  return new Proxy(model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v3\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-embedding-model-v4.ts\nfunction asEmbeddingModelV4(model) {\n  if (model.specificationVersion === \"v4\") {\n    return model;\n  }\n  const v3Model = model.specificationVersion === \"v2\" ? asEmbeddingModelV3(model) : model;\n  return new Proxy(v3Model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v4\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-image-model-v3.ts\nfunction asImageModelV3(model) {\n  if (model.specificationVersion === \"v3\") {\n    return model;\n  }\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId\n  });\n  return new Proxy(model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v3\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-image-model-v4.ts\nfunction asImageModelV4(model) {\n  if (model.specificationVersion === \"v4\") {\n    return model;\n  }\n  const v3Model = model.specificationVersion === \"v2\" ? asImageModelV3(model) : model;\n  return new Proxy(v3Model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v4\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-language-model-v3.ts\nfunction asLanguageModelV3(model) {\n  if (model.specificationVersion === \"v3\") {\n    return model;\n  }\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId\n  });\n  return new Proxy(model, {\n    get(target, prop) {\n      switch (prop) {\n        case \"specificationVersion\":\n          return \"v3\";\n        case \"doGenerate\":\n          return async (...args) => {\n            const result = await target.doGenerate(...args);\n            return {\n              ...result,\n              finishReason: convertV2FinishReasonToV3(result.finishReason),\n              usage: convertV2UsageToV3(result.usage)\n            };\n          };\n        case \"doStream\":\n          return async (...args) => {\n            const result = await target.doStream(...args);\n            return {\n              ...result,\n              stream: convertV2StreamToV3(result.stream)\n            };\n          };\n        default:\n          return target[prop];\n      }\n    }\n  });\n}\nfunction convertV2StreamToV3(stream) {\n  return stream.pipeThrough(\n    new TransformStream({\n      transform(chunk, controller) {\n        switch (chunk.type) {\n          case \"finish\":\n            controller.enqueue({\n              ...chunk,\n              finishReason: convertV2FinishReasonToV3(chunk.finishReason),\n              usage: convertV2UsageToV3(chunk.usage)\n            });\n            break;\n          default:\n            controller.enqueue(chunk);\n            break;\n        }\n      }\n    })\n  );\n}\nfunction convertV2FinishReasonToV3(finishReason) {\n  return {\n    unified: finishReason === \"unknown\" ? \"other\" : finishReason,\n    raw: void 0\n  };\n}\nfunction convertV2UsageToV3(usage) {\n  return {\n    inputTokens: {\n      total: usage.inputTokens,\n      noCache: void 0,\n      cacheRead: usage.cachedInputTokens,\n      cacheWrite: void 0\n    },\n    outputTokens: {\n      total: usage.outputTokens,\n      text: void 0,\n      reasoning: usage.reasoningTokens\n    }\n  };\n}\n\n// src/model/as-language-model-v4.ts\nfunction asLanguageModelV4(model) {\n  if (model.specificationVersion === \"v4\") {\n    return model;\n  }\n  const v3Model = model.specificationVersion === \"v2\" ? asLanguageModelV3(model) : model;\n  return new Proxy(v3Model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v4\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-reranking-model-v4.ts\nfunction asRerankingModelV4(model) {\n  if (model.specificationVersion === \"v4\") {\n    return model;\n  }\n  return new Proxy(model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v4\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-speech-model-v3.ts\nfunction asSpeechModelV3(model) {\n  if (model.specificationVersion === \"v3\") {\n    return model;\n  }\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId\n  });\n  return new Proxy(model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v3\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-speech-model-v4.ts\nfunction asSpeechModelV4(model) {\n  if (model.specificationVersion === \"v4\") {\n    return model;\n  }\n  const v3Model = model.specificationVersion === \"v2\" ? asSpeechModelV3(model) : model;\n  return new Proxy(v3Model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v4\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-transcription-model-v3.ts\nfunction asTranscriptionModelV3(model) {\n  if (model.specificationVersion === \"v3\") {\n    return model;\n  }\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId\n  });\n  return new Proxy(model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v3\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-transcription-model-v4.ts\nfunction asTranscriptionModelV4(model) {\n  if (model.specificationVersion === \"v4\") {\n    return model;\n  }\n  const v3Model = model.specificationVersion === \"v2\" ? asTranscriptionModelV3(model) : model;\n  return new Proxy(v3Model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v4\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-video-model-v4.ts\nfunction asVideoModelV4(model) {\n  if (model.specificationVersion === \"v4\") {\n    return model;\n  }\n  return new Proxy(model, {\n    get(target, prop) {\n      if (prop === \"specificationVersion\")\n        return \"v4\";\n      return target[prop];\n    }\n  });\n}\n\n// src/model/as-provider-v3.ts\nfunction asProviderV3(provider) {\n  if (\"specificationVersion\" in provider && provider.specificationVersion === \"v3\") {\n    return provider;\n  }\n  const v2Provider = provider;\n  return {\n    specificationVersion: \"v3\",\n    languageModel: (modelId) => asLanguageModelV3(v2Provider.languageModel(modelId)),\n    embeddingModel: (modelId) => asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n    imageModel: (modelId) => asImageModelV3(v2Provider.imageModel(modelId)),\n    transcriptionModel: v2Provider.transcriptionModel ? (modelId) => asTranscriptionModelV3(v2Provider.transcriptionModel(modelId)) : void 0,\n    speechModel: v2Provider.speechModel ? (modelId) => asSpeechModelV3(v2Provider.speechModel(modelId)) : void 0,\n    rerankingModel: void 0\n    // v2 providers don't have reranking models\n  };\n}\n\n// src/model/as-provider-v4.ts\nfunction asProviderV4(provider) {\n  if (\"specificationVersion\" in provider && provider.specificationVersion === \"v4\") {\n    return provider;\n  }\n  const v3Provider = !(\"specificationVersion\" in provider) || provider.specificationVersion !== \"v3\" ? asProviderV3(provider) : provider;\n  return {\n    specificationVersion: \"v4\",\n    languageModel: (modelId) => asLanguageModelV4(v3Provider.languageModel(modelId)),\n    embeddingModel: (modelId) => asEmbeddingModelV4(v3Provider.embeddingModel(modelId)),\n    imageModel: (modelId) => asImageModelV4(v3Provider.imageModel(modelId)),\n    transcriptionModel: v3Provider.transcriptionModel ? (modelId) => asTranscriptionModelV4(v3Provider.transcriptionModel(modelId)) : void 0,\n    speechModel: v3Provider.speechModel ? (modelId) => asSpeechModelV4(v3Provider.speechModel(modelId)) : void 0,\n    rerankingModel: v3Provider.rerankingModel ? (modelId) => asRerankingModelV4(v3Provider.rerankingModel(modelId)) : void 0\n  };\n}\n\n// src/model/resolve-model.ts\nfunction resolveLanguageModel(model) {\n  if (typeof model === \"string\") {\n    return getGlobalProvider().languageModel(model);\n  }\n  if (![\"v4\", \"v3\", \"v2\"].includes(model.specificationVersion)) {\n    const unsupportedModel = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId\n    });\n  }\n  return asLanguageModelV4(model);\n}\nfunction resolveEmbeddingModel(model) {\n  if (typeof model === \"string\") {\n    return getGlobalProvider().embeddingModel(model);\n  }\n  if (![\"v4\", \"v3\", \"v2\"].includes(model.specificationVersion)) {\n    const unsupportedModel = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId\n    });\n  }\n  return asEmbeddingModelV4(model);\n}\nfunction resolveTranscriptionModel(model) {\n  var _a22, _b;\n  if (typeof model === \"string\") {\n    return (_b = (_a22 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a22, model);\n  }\n  if (![\"v4\", \"v3\", \"v2\"].includes(model.specificationVersion)) {\n    const unsupportedModel = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId\n    });\n  }\n  return asTranscriptionModelV4(model);\n}\nfunction resolveSpeechModel(model) {\n  var _a22, _b;\n  if (typeof model === \"string\") {\n    return (_b = (_a22 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a22, model);\n  }\n  if (![\"v4\", \"v3\", \"v2\"].includes(model.specificationVersion)) {\n    const unsupportedModel = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId\n    });\n  }\n  return asSpeechModelV4(model);\n}\nfunction resolveImageModel(model) {\n  if (typeof model === \"string\") {\n    return getGlobalProvider().imageModel(model);\n  }\n  if (![\"v4\", \"v3\", \"v2\"].includes(model.specificationVersion)) {\n    const unsupportedModel = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId\n    });\n  }\n  return asImageModelV4(model);\n}\nfunction resolveVideoModel(model) {\n  var _a22;\n  if (typeof model === \"string\") {\n    const provider = (_a22 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a22 : gateway;\n    const videoModel = provider.videoModel;\n    if (!videoModel) {\n      throw new Error(\n        'The default provider does not support video models. Please use a Experimental_VideoModelV4 object from a provider (e.g., vertex.video(\"model-id\")).'\n      );\n    }\n    return videoModel(model);\n  }\n  if (![\"v4\", \"v3\"].includes(model.specificationVersion)) {\n    const unsupportedModel = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId\n    });\n  }\n  return asVideoModelV4(model);\n}\nfunction resolveRerankingModel(model) {\n  if (typeof model === \"string\") {\n    const provider = getGlobalProvider();\n    const rerankingModel = provider.rerankingModel;\n    if (!rerankingModel) {\n      throw new Error(\n        'The default provider does not support reranking models. Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\"model-id\")).'\n      );\n    }\n    return rerankingModel(model);\n  }\n  if (model.specificationVersion !== \"v4\" && model.specificationVersion !== \"v3\") {\n    const unsupportedModel = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId\n    });\n  }\n  return asRerankingModelV4(model);\n}\nfunction getGlobalProvider() {\n  var _a22;\n  const provider = (_a22 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a22 : gateway;\n  return asProviderV4(provider);\n}\n\n// src/prompt/clone-model-message.ts\nfunction cloneModelMessages(messages) {\n  return messages.map((message) => cloneValue(message));\n}\nfunction cloneValue(value) {\n  if (value instanceof URL) {\n    return new URL(value.href);\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) => cloneValue(item));\n  }\n  if (value instanceof Uint8Array) {\n    return new Uint8Array(value);\n  }\n  if (value instanceof ArrayBuffer) {\n    return value.slice(0);\n  }\n  if (value instanceof Date) {\n    return new Date(value);\n  }\n  if (value != null && typeof value === \"object\") {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, value2]) => [key, cloneValue(value2)])\n    );\n  }\n  return value;\n}\n\n// src/prompt/convert-to-language-model-prompt.ts\nimport {\n  asArray,\n  detectMediaType,\n  isFullMediaType,\n  isUrlSupported\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/download/download.ts\nimport {\n  cancelResponseBody,\n  DownloadError as DownloadError2,\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n  fetchWithValidatedRedirects,\n  withUserAgentSuffix,\n  getRuntimeEnvironmentUserAgent\n} from \"@ai-sdk/provider-utils\";\n\n// src/version.ts\nvar VERSION = true ? \"7.0.4\" : \"0.0.0-test\";\n\n// src/util/download/download.ts\nvar download = async ({\n  url,\n  maxBytes,\n  abortSignal\n}) => {\n  var _a22;\n  const urlText = url.toString();\n  try {\n    const headers = withUserAgentSuffix(\n      {},\n      `ai-sdk/${VERSION}`,\n      getRuntimeEnvironmentUserAgent()\n    );\n    const response = await fetchWithValidatedRedirects({\n      url: urlText,\n      headers,\n      abortSignal\n    });\n    if (!response.ok) {\n      await cancelResponseBody(response);\n      throw new DownloadError2({\n        url: urlText,\n        statusCode: response.status,\n        statusText: response.statusText\n      });\n    }\n    const data = await readResponseWithSizeLimit({\n      response,\n      url: urlText,\n      maxBytes: maxBytes != null ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE\n    });\n    return {\n      data,\n      mediaType: (_a22 = response.headers.get(\"content-type\")) != null ? _a22 : void 0\n    };\n  } catch (error) {\n    if (DownloadError2.isInstance(error)) {\n      throw error;\n    }\n    throw new DownloadError2({ url: urlText, cause: error });\n  }\n};\n\n// src/util/download/download-function.ts\nvar createDefaultDownloadFunction = (download2 = download) => (requestedDownloads) => Promise.all(\n  requestedDownloads.map(\n    async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : await download2(requestedDownload)\n  )\n);\n\n// src/prompt/file-part-data.ts\nimport {\n  isBuffer,\n  isProviderReference\n} from \"@ai-sdk/provider-utils\";\n\n// src/prompt/split-data-url.ts\nfunction splitDataUrl(dataUrl) {\n  try {\n    const [header, base64Content] = dataUrl.split(\",\");\n    return {\n      mediaType: header.split(\";\")[0].split(\":\")[1],\n      base64Content\n    };\n  } catch (e) {\n    return {\n      mediaType: void 0,\n      base64Content: void 0\n    };\n  }\n}\n\n// src/prompt/file-part-data.ts\nfunction isTaggedFileData(value) {\n  if (typeof value !== \"object\" || value === null)\n    return false;\n  const type = value.type;\n  return type === \"data\" || type === \"url\" || type === \"reference\" || type === \"text\";\n}\nfunction convertUrlToFilePartData(url) {\n  if (url.protocol === \"data:\") {\n    const { mediaType, base64Content } = splitDataUrl(url.toString());\n    if (mediaType == null || base64Content == null) {\n      throw new InvalidDataContentError({\n        content: url,\n        message: `Invalid data URL format in content ${url.toString()}`\n      });\n    }\n    return { data: { type: \"data\", data: base64Content }, mediaType };\n  }\n  return { data: { type: \"url\", url }, mediaType: void 0 };\n}\nfunction convertInlineDataToFilePartData(content) {\n  if (content instanceof Uint8Array) {\n    return { data: { type: \"data\", data: content }, mediaType: void 0 };\n  }\n  if (content instanceof ArrayBuffer) {\n    return {\n      data: { type: \"data\", data: new Uint8Array(content) },\n      mediaType: void 0\n    };\n  }\n  if (isBuffer(content)) {\n    return {\n      data: { type: \"data\", data: new Uint8Array(content) },\n      mediaType: void 0\n    };\n  }\n  return {\n    data: { type: \"data\", data: content },\n    mediaType: void 0\n  };\n}\nfunction convertToLanguageModelV4FilePart(content) {\n  if (isTaggedFileData(content)) {\n    switch (content.type) {\n      case \"data\":\n        if (typeof content.data === \"string\" && content.data.startsWith(\"data:\")) {\n          throw new InvalidDataContentError({\n            content: content.data,\n            message: 'Data URLs are not valid inline data. Pass them as { type: \"url\", url } instead.'\n          });\n        }\n        return convertInlineDataToFilePartData(content.data);\n      case \"url\":\n        return convertUrlToFilePartData(content.url);\n      case \"reference\":\n        return {\n          data: { type: \"reference\", reference: content.reference },\n          mediaType: void 0\n        };\n      case \"text\":\n        return {\n          data: { type: \"text\", text: content.text },\n          mediaType: void 0\n        };\n    }\n  }\n  if (content instanceof URL) {\n    return convertUrlToFilePartData(content);\n  }\n  if (typeof content === \"string\") {\n    try {\n      return convertUrlToFilePartData(new URL(content));\n    } catch (e) {\n      return convertInlineDataToFilePartData(content);\n    }\n  }\n  if (isProviderReference(content)) {\n    return {\n      data: { type: \"reference\", reference: content },\n      mediaType: void 0\n    };\n  }\n  return convertInlineDataToFilePartData(content);\n}\n\n// src/prompt/convert-to-language-model-prompt.ts\nasync function convertToLanguageModelPrompt({\n  prompt,\n  supportedUrls,\n  download: download2 = createDefaultDownloadFunction(),\n  // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n  // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n  provider\n}) {\n  const downloadedAssets = await downloadAssets(\n    prompt.messages,\n    download2,\n    supportedUrls\n  );\n  const approvalIdToToolCallId = /* @__PURE__ */ new Map();\n  for (const message of prompt.messages) {\n    if (message.role === \"assistant\" && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        if (part.type === \"tool-approval-request\" && \"approvalId\" in part && \"toolCallId\" in part) {\n          approvalIdToToolCallId.set(\n            part.approvalId,\n            part.toolCallId\n          );\n        }\n      }\n    }\n  }\n  const approvedToolCallIds = /* @__PURE__ */ new Set();\n  for (const message of prompt.messages) {\n    if (message.role === \"tool\") {\n      for (const part of message.content) {\n        if (part.type === \"tool-approval-response\") {\n          const toolCallId = approvalIdToToolCallId.get(part.approvalId);\n          if (toolCallId) {\n            approvedToolCallIds.add(toolCallId);\n          }\n        }\n      }\n    }\n  }\n  const messages = [\n    ...prompt.instructions != null ? typeof prompt.instructions === \"string\" ? [{ role: \"system\", content: prompt.instructions }] : asArray(prompt.instructions).map((message) => ({\n      role: \"system\",\n      content: message.content,\n      providerOptions: message.providerOptions\n    })) : [],\n    ...prompt.messages.map(\n      (message) => convertToLanguageModelMessage({ message, downloadedAssets, provider })\n    )\n  ];\n  const combinedMessages = [];\n  for (const message of messages) {\n    if (message.role !== \"tool\") {\n      combinedMessages.push(message);\n      continue;\n    }\n    const lastCombinedMessage = combinedMessages.at(-1);\n    if ((lastCombinedMessage == null ? void 0 : lastCombinedMessage.role) === \"tool\") {\n      lastCombinedMessage.content.push(...message.content);\n    } else {\n      combinedMessages.push(message);\n    }\n  }\n  const toolCallIds = /* @__PURE__ */ new Set();\n  for (const message of combinedMessages) {\n    switch (message.role) {\n      case \"assistant\": {\n        for (const content of message.content) {\n          if (content.type === \"tool-call\" && !content.providerExecuted) {\n            toolCallIds.add(content.toolCallId);\n          }\n        }\n        break;\n      }\n      case \"tool\": {\n        for (const content of message.content) {\n          if (content.type === \"tool-result\") {\n            toolCallIds.delete(content.toolCallId);\n          }\n        }\n        break;\n      }\n      case \"user\":\n      case \"system\":\n        for (const id of approvedToolCallIds) {\n          toolCallIds.delete(id);\n        }\n        if (toolCallIds.size > 0) {\n          throw new MissingToolResultsError({\n            toolCallIds: Array.from(toolCallIds)\n          });\n        }\n        break;\n    }\n  }\n  for (const id of approvedToolCallIds) {\n    toolCallIds.delete(id);\n  }\n  if (toolCallIds.size > 0) {\n    throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n  }\n  return combinedMessages.filter(\n    // Filter out empty tool messages (e.g. if they only contained\n    // tool-approval-response parts that were removed).\n    // This prevents sending invalid empty messages to the provider.\n    // Note: provider-executed tool-approval-response parts are preserved.\n    (message) => message.role !== \"tool\" || message.content.length > 0\n  );\n}\nfunction convertToLanguageModelMessage({\n  message,\n  downloadedAssets,\n  // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n  // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n  provider\n}) {\n  const warnings = [];\n  const role = message.role;\n  switch (role) {\n    case \"system\": {\n      return {\n        role: \"system\",\n        content: message.content,\n        providerOptions: message.providerOptions\n      };\n    }\n    case \"user\": {\n      if (typeof message.content === \"string\") {\n        return {\n          role: \"user\",\n          content: [{ type: \"text\", text: message.content }],\n          providerOptions: message.providerOptions\n        };\n      }\n      const converted = {\n        role: \"user\",\n        content: message.content.map((part) => {\n          if (part.type === \"image\") {\n            warnings.push({\n              type: \"deprecated\",\n              setting: '\"image\" content part',\n              message: `The \"image\" content part type is deprecated. Use a \"file\" part with mediaType: 'image' (or a more specific image/* subtype) instead.`\n            });\n          }\n          return convertImagePartToFilePart(part);\n        }).map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== \"text\" || part.text !== \"\"),\n        providerOptions: message.providerOptions\n      };\n      if (warnings.length > 0) {\n        logWarnings({ warnings });\n      }\n      return converted;\n    }\n    case \"assistant\": {\n      if (typeof message.content === \"string\") {\n        return {\n          role: \"assistant\",\n          content: [{ type: \"text\", text: message.content }],\n          providerOptions: message.providerOptions\n        };\n      }\n      const converted = {\n        role: \"assistant\",\n        content: message.content.filter(\n          // remove empty text parts (no text, and no provider options):\n          (part) => part.type !== \"text\" || part.text !== \"\" || part.providerOptions != null\n        ).filter(\n          (part) => part.type !== \"tool-approval-request\"\n        ).map((part) => {\n          const providerOptions = part.providerOptions;\n          switch (part.type) {\n            case \"custom\": {\n              return {\n                type: \"custom\",\n                kind: part.kind,\n                providerOptions\n              };\n            }\n            case \"file\": {\n              const { data, mediaType } = convertToLanguageModelV4FilePart(\n                part.data\n              );\n              return {\n                type: \"file\",\n                data,\n                filename: part.filename,\n                mediaType: mediaType != null ? mediaType : part.mediaType,\n                providerOptions\n              };\n            }\n            case \"reasoning\": {\n              return {\n                type: \"reasoning\",\n                text: part.text,\n                providerOptions\n              };\n            }\n            case \"reasoning-file\": {\n              const { data, mediaType } = convertToLanguageModelV4FilePart(\n                part.data\n              );\n              if (data.type !== \"data\" && data.type !== \"url\") {\n                throw new Error(\n                  `Unsupported reasoning-file data type: ${data.type}`\n                );\n              }\n              return {\n                type: \"reasoning-file\",\n                data,\n                mediaType: mediaType != null ? mediaType : part.mediaType,\n                providerOptions\n              };\n            }\n            case \"text\": {\n              return {\n                type: \"text\",\n                text: part.text,\n                providerOptions\n              };\n            }\n            case \"tool-call\": {\n              return {\n                type: \"tool-call\",\n                toolCallId: part.toolCallId,\n                toolName: part.toolName,\n                input: part.input,\n                providerExecuted: part.providerExecuted,\n                providerOptions\n              };\n            }\n            case \"tool-result\": {\n              return {\n                type: \"tool-result\",\n                toolCallId: part.toolCallId,\n                toolName: part.toolName,\n                output: mapToolResultOutput({\n                  output: part.output,\n                  provider,\n                  warnings,\n                  downloadedAssets\n                }),\n                providerOptions\n              };\n            }\n          }\n        }),\n        providerOptions: message.providerOptions\n      };\n      if (warnings.length > 0) {\n        logWarnings({ warnings });\n      }\n      return converted;\n    }\n    case \"tool\": {\n      const converted = {\n        role: \"tool\",\n        content: message.content.filter(\n          // Only include tool-approval-response for provider-executed tools\n          (part) => part.type !== \"tool-approval-response\" || part.providerExecuted\n        ).map((part) => {\n          switch (part.type) {\n            case \"tool-result\": {\n              return {\n                type: \"tool-result\",\n                toolCallId: part.toolCallId,\n                toolName: part.toolName,\n                output: mapToolResultOutput({\n                  output: part.output,\n                  provider,\n                  warnings,\n                  downloadedAssets\n                }),\n                providerOptions: part.providerOptions\n              };\n            }\n            case \"tool-approval-response\": {\n              return {\n                type: \"tool-approval-response\",\n                approvalId: part.approvalId,\n                approved: part.approved,\n                reason: part.reason\n              };\n            }\n          }\n        }),\n        providerOptions: message.providerOptions\n      };\n      if (warnings.length > 0) {\n        logWarnings({ warnings });\n      }\n      return converted;\n    }\n    default: {\n      const _exhaustiveCheck = role;\n      throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n    }\n  }\n}\nfunction convertImagePartToFilePart(part) {\n  var _a22;\n  if (part.type !== \"image\") {\n    return part;\n  }\n  return {\n    type: \"file\",\n    data: part.image,\n    mediaType: (_a22 = part.mediaType) != null ? _a22 : \"image\",\n    providerOptions: part.providerOptions\n  };\n}\nasync function downloadAssets(messages, download2, supportedUrls) {\n  const downloadableFiles = [];\n  for (const message of messages) {\n    if (message.role === \"user\" && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        const filePart = convertImagePartToFilePart(part);\n        if (filePart.type === \"file\") {\n          downloadableFiles.push(filePart);\n        }\n      }\n    }\n    if (message.role === \"tool\") {\n      for (const part of message.content) {\n        if (part.type !== \"tool-result\") {\n          continue;\n        }\n        if (part.output.type !== \"content\") {\n          continue;\n        }\n        for (const contentPart of part.output.value) {\n          if (contentPart.type === \"file\") {\n            downloadableFiles.push(contentPart);\n          }\n        }\n      }\n    }\n    if (message.role === \"assistant\" && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        if (part.type !== \"tool-result\") {\n          continue;\n        }\n        if (part.output.type !== \"content\") {\n          continue;\n        }\n        for (const contentPart of part.output.value) {\n          if (contentPart.type === \"file\") {\n            downloadableFiles.push(contentPart);\n          }\n        }\n      }\n    }\n  }\n  const plannedDownloads = downloadableFiles.map((part) => {\n    const mediaType = part.mediaType;\n    const { data } = convertToLanguageModelV4FilePart(part.data);\n    return { mediaType, data };\n  }).filter((part) => part.data.type === \"url\").map((part) => ({\n    url: part.data.url,\n    isUrlSupportedByModel: part.mediaType != null && isUrlSupported({\n      url: part.data.url.toString(),\n      mediaType: part.mediaType,\n      supportedUrls\n    })\n  }));\n  const downloadedFiles = await download2(plannedDownloads);\n  return Object.fromEntries(\n    downloadedFiles.map(\n      (file, index) => file == null ? null : [\n        plannedDownloads[index].url.toString(),\n        { data: file.data, mediaType: file.mediaType }\n      ]\n    ).filter((file) => file != null)\n  );\n}\nfunction convertPartToLanguageModelPart(part, downloadedAssets) {\n  if (part.type === \"text\") {\n    return {\n      type: \"text\",\n      text: part.text,\n      providerOptions: part.providerOptions\n    };\n  }\n  const { data: normalizedData, mediaType: dataUrlMediaType } = convertToLanguageModelV4FilePart(part.data);\n  let mediaType = dataUrlMediaType != null ? dataUrlMediaType : part.mediaType;\n  let data = normalizedData;\n  if (data.type === \"url\") {\n    const downloadedFile = downloadedAssets[data.url.toString()];\n    if (downloadedFile) {\n      data = { type: \"data\", data: downloadedFile.data };\n      if (downloadedFile.mediaType != null && (mediaType == null || !isFullMediaType(mediaType))) {\n        mediaType = downloadedFile.mediaType;\n      }\n    }\n  }\n  if (data.type === \"data\" && (data.data instanceof Uint8Array || typeof data.data === \"string\")) {\n    const imageMediaType = detectMediaType({\n      data: data.data,\n      topLevelType: \"image\"\n    });\n    if (imageMediaType != null) {\n      mediaType = imageMediaType;\n    }\n  }\n  if (mediaType == null) {\n    throw new Error(`Media type is missing for file part`);\n  }\n  return {\n    type: \"file\",\n    mediaType,\n    filename: part.filename,\n    data,\n    providerOptions: part.providerOptions\n  };\n}\nfunction mapToolResultOutput({\n  output,\n  // `provider` is only needed here to convert legacy \"file-id\" and \"image-file-id\" types to provider references, in case they are using string ID values.\n  // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n  provider,\n  warnings = [],\n  downloadedAssets\n}) {\n  if (output.type !== \"content\") {\n    return output;\n  }\n  return {\n    type: \"content\",\n    value: output.value.map((item) => {\n      var _a22;\n      switch (item.type) {\n        case \"file\": {\n          const convertedPart = convertPartToLanguageModelPart(\n            item,\n            downloadedAssets\n          );\n          if (convertedPart.type !== \"file\") {\n            throw new Error(\n              \"Expected tool result file content to convert to file.\"\n            );\n          }\n          return convertedPart;\n        }\n        case \"file-data\": {\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"file-data\"',\n            message: `The \"file-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`\n          });\n          return {\n            type: \"file\",\n            data: { type: \"data\", data: item.data },\n            filename: item.filename,\n            mediaType: item.mediaType,\n            providerOptions: item.providerOptions\n          };\n        }\n        case \"file-url\": {\n          const mediaType = (_a22 = item.mediaType) != null ? _a22 : getMediaTypeFromUrl(item.url);\n          let message = `The \"file-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'url', url } instead.`;\n          if (!item.mediaType) {\n            const inferenceSuffix = mediaType === \"application/octet-stream\" ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.` : `Inferred media type '${mediaType}' from URL.`;\n            message = `The \"file-url\" tool result content part with URL \"${item.url}\" is missing a \"mediaType\". ${inferenceSuffix} ${message}`;\n          }\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"file-url\"',\n            message\n          });\n          return {\n            type: \"file\",\n            data: { type: \"url\", url: new URL(item.url) },\n            mediaType,\n            providerOptions: item.providerOptions\n          };\n        }\n        case \"file-id\": {\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"file-id\"',\n            message: `The \"file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n          });\n          return {\n            type: \"file\",\n            data: {\n              type: \"reference\",\n              reference: convertFileIdToProviderReference({\n                fileId: item.fileId,\n                provider\n              })\n            },\n            mediaType: \"application\",\n            providerOptions: item.providerOptions\n          };\n        }\n        case \"file-reference\": {\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"file-reference\"',\n            message: `The \"file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n          });\n          return {\n            type: \"file\",\n            data: {\n              type: \"reference\",\n              reference: item.providerReference\n            },\n            mediaType: \"application\",\n            providerOptions: item.providerOptions\n          };\n        }\n        case \"image-data\": {\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"image-data\"',\n            message: `The \"image-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`\n          });\n          return {\n            type: \"file\",\n            data: { type: \"data\", data: item.data },\n            mediaType: item.mediaType,\n            providerOptions: item.providerOptions\n          };\n        }\n        case \"image-url\": {\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"image-url\"',\n            message: `The \"image-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType 'image' (or a specific image/* subtype) and { type: 'url', url } instead.`\n          });\n          return {\n            type: \"file\",\n            data: { type: \"url\", url: new URL(item.url) },\n            mediaType: \"image\",\n            providerOptions: item.providerOptions\n          };\n        }\n        case \"image-file-id\": {\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"image-file-id\"',\n            message: `The \"image-file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n          });\n          return {\n            type: \"file\",\n            data: {\n              type: \"reference\",\n              reference: convertFileIdToProviderReference({\n                fileId: item.fileId,\n                provider\n              })\n            },\n            mediaType: \"image\",\n            providerOptions: item.providerOptions\n          };\n        }\n        case \"image-file-reference\": {\n          warnings.push({\n            type: \"deprecated\",\n            setting: '\"tool-result\" content of type \"image-file-reference\"',\n            message: `The \"image-file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n          });\n          return {\n            type: \"file\",\n            data: {\n              type: \"reference\",\n              reference: item.providerReference\n            },\n            mediaType: \"image\",\n            providerOptions: item.providerOptions\n          };\n        }\n        default:\n          return item;\n      }\n    })\n  };\n}\nfunction convertFileIdToProviderReference({\n  fileId,\n  provider\n}) {\n  if (typeof fileId === \"object\") {\n    return fileId;\n  }\n  if (provider == null) {\n    throw new Error(\n      \"Cannot convert string fileId to provider reference without a provider ID. Use a Record<string, string> fileId or switch to the file-reference type.\"\n    );\n  }\n  return { [provider]: fileId };\n}\nvar URL_EXTENSION_TO_MEDIA_TYPE = {\n  jpg: \"image/jpeg\",\n  jpeg: \"image/jpeg\",\n  png: \"image/png\",\n  gif: \"image/gif\",\n  webp: \"image/webp\",\n  svg: \"image/svg+xml\",\n  avif: \"image/avif\",\n  heic: \"image/heic\",\n  bmp: \"image/bmp\",\n  tiff: \"image/tiff\",\n  tif: \"image/tiff\",\n  pdf: \"application/pdf\",\n  mp4: \"video/mp4\",\n  webm: \"video/webm\",\n  mp3: \"audio/mpeg\",\n  wav: \"audio/wav\",\n  ogg: \"audio/ogg\"\n};\nfunction getMediaTypeFromUrl(url, fallbackMediaType = \"application/octet-stream\") {\n  var _a22;\n  try {\n    const pathname = new URL(url).pathname;\n    const fileExtension = (_a22 = pathname.split(\".\").pop()) == null ? void 0 : _a22.toLowerCase();\n    if (fileExtension && Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension)) {\n      return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension];\n    }\n  } catch (e) {\n  }\n  return fallbackMediaType;\n}\n\n// src/prompt/create-tool-model-output.ts\nimport { getErrorMessage as getErrorMessage3 } from \"@ai-sdk/provider\";\nasync function createToolModelOutput({\n  toolCallId,\n  input,\n  output,\n  tool: tool2,\n  errorMode\n}) {\n  if (errorMode === \"text\") {\n    return { type: \"error-text\", value: getErrorMessage3(output) };\n  } else if (errorMode === \"json\") {\n    return { type: \"error-json\", value: toJSONValue(output) };\n  }\n  if (tool2 == null ? void 0 : tool2.toModelOutput) {\n    return await tool2.toModelOutput({ toolCallId, input, output });\n  }\n  return typeof output === \"string\" ? { type: \"text\", value: output } : { type: \"json\", value: toJSONValue(output) };\n}\nfunction toJSONValue(value) {\n  return value === void 0 ? null : value;\n}\n\n// src/prompt/prepare-language-model-call-options.ts\nfunction prepareLanguageModelCallOptions({\n  maxOutputTokens,\n  temperature,\n  topP,\n  topK,\n  presencePenalty,\n  frequencyPenalty,\n  seed,\n  stopSequences,\n  reasoning\n}) {\n  if (maxOutputTokens != null) {\n    if (!Number.isInteger(maxOutputTokens)) {\n      throw new InvalidArgumentError({\n        parameter: \"maxOutputTokens\",\n        value: maxOutputTokens,\n        message: \"maxOutputTokens must be an integer\"\n      });\n    }\n    if (maxOutputTokens < 1) {\n      throw new InvalidArgumentError({\n        parameter: \"maxOutputTokens\",\n        value: maxOutputTokens,\n        message: \"maxOutputTokens must be >= 1\"\n      });\n    }\n  }\n  if (temperature != null) {\n    if (typeof temperature !== \"number\") {\n      throw new InvalidArgumentError({\n        parameter: \"temperature\",\n        value: temperature,\n        message: \"temperature must be a number\"\n      });\n    }\n  }\n  if (topP != null) {\n    if (typeof topP !== \"number\") {\n      throw new InvalidArgumentError({\n        parameter: \"topP\",\n        value: topP,\n        message: \"topP must be a number\"\n      });\n    }\n  }\n  if (topK != null) {\n    if (typeof topK !== \"number\") {\n      throw new InvalidArgumentError({\n        parameter: \"topK\",\n        value: topK,\n        message: \"topK must be a number\"\n      });\n    }\n  }\n  if (presencePenalty != null) {\n    if (typeof presencePenalty !== \"number\") {\n      throw new InvalidArgumentError({\n        parameter: \"presencePenalty\",\n        value: presencePenalty,\n        message: \"presencePenalty must be a number\"\n      });\n    }\n  }\n  if (frequencyPenalty != null) {\n    if (typeof frequencyPenalty !== \"number\") {\n      throw new InvalidArgumentError({\n        parameter: \"frequencyPenalty\",\n        value: frequencyPenalty,\n        message: \"frequencyPenalty must be a number\"\n      });\n    }\n  }\n  if (seed != null) {\n    if (!Number.isInteger(seed)) {\n      throw new InvalidArgumentError({\n        parameter: \"seed\",\n        value: seed,\n        message: \"seed must be an integer\"\n      });\n    }\n  }\n  return {\n    maxOutputTokens,\n    temperature,\n    topP,\n    topK,\n    presencePenalty,\n    frequencyPenalty,\n    stopSequences,\n    seed,\n    reasoning\n  };\n}\n\n// src/prompt/prepare-tool-choice.ts\nfunction prepareToolChoice({\n  toolChoice\n}) {\n  return toolChoice == null ? { type: \"auto\" } : typeof toolChoice === \"string\" ? { type: toolChoice } : { type: \"tool\", toolName: toolChoice.toolName };\n}\n\n// src/prompt/prepare-tools.ts\nimport {\n  asSchema\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/is-non-empty-object.ts\nfunction isNonEmptyObject(object2) {\n  return object2 != null && Object.keys(object2).length > 0;\n}\n\n// src/prompt/prepare-tools.ts\nasync function prepareTools({\n  tools,\n  toolOrder,\n  toolsContext = {},\n  experimental_sandbox: sandbox\n}) {\n  if (!isNonEmptyObject(tools)) {\n    return void 0;\n  }\n  const languageModelTools = [];\n  for (const [name22, tool2] of orderToolEntries({ tools, toolOrder })) {\n    const toolType = tool2.type;\n    switch (toolType) {\n      case void 0:\n      case \"dynamic\":\n      case \"function\": {\n        const description = resolveToolDescription({\n          tool: tool2,\n          toolName: name22,\n          toolsContext,\n          experimental_sandbox: sandbox\n        });\n        const providerOptions = tool2.providerOptions;\n        const inputExamples = tool2.inputExamples;\n        const strict = tool2.strict;\n        languageModelTools.push({\n          type: \"function\",\n          name: name22,\n          inputSchema: await asSchema(tool2.inputSchema).jsonSchema,\n          ...description != null ? { description } : {},\n          ...inputExamples != null ? { inputExamples } : {},\n          ...providerOptions != null ? { providerOptions } : {},\n          ...strict != null ? { strict } : {}\n        });\n        break;\n      }\n      case \"provider\": {\n        languageModelTools.push({\n          type: \"provider\",\n          name: name22,\n          id: tool2.id,\n          args: tool2.args\n        });\n        break;\n      }\n      default: {\n        const exhaustiveCheck = toolType;\n        throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n      }\n    }\n  }\n  return languageModelTools;\n}\nfunction orderToolEntries({\n  tools,\n  toolOrder\n}) {\n  if (toolOrder == null) {\n    return Object.entries(tools);\n  }\n  const toolEntries = Object.entries(tools);\n  const orderedTools = toolEntries.filter(([name22]) => toolOrder.includes(name22)).sort(\n    ([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB)\n  );\n  const unorderedTools = toolEntries.filter(([name22]) => !toolOrder.includes(name22)).sort(([nameA], [nameB]) => nameA < nameB ? -1 : nameA > nameB ? 1 : 0);\n  return [...orderedTools, ...unorderedTools];\n}\nfunction resolveToolDescription({\n  tool: tool2,\n  toolName,\n  toolsContext,\n  experimental_sandbox: sandbox\n}) {\n  return tool2.description === void 0 ? void 0 : typeof tool2.description === \"string\" ? tool2.description : tool2.description({\n    context: toolsContext[toolName],\n    experimental_sandbox: sandbox\n  });\n}\n\n// src/prompt/request-options.ts\nfunction getTotalTimeoutMs(timeout) {\n  if (timeout == null) {\n    return void 0;\n  }\n  if (typeof timeout === \"number\") {\n    return timeout;\n  }\n  return timeout.totalMs;\n}\nfunction getStepTimeoutMs(timeout) {\n  if (timeout == null || typeof timeout === \"number\") {\n    return void 0;\n  }\n  return timeout.stepMs;\n}\nfunction getChunkTimeoutMs(timeout) {\n  if (timeout == null || typeof timeout === \"number\") {\n    return void 0;\n  }\n  return timeout.chunkMs;\n}\nfunction getToolTimeoutMs(timeout, toolName) {\n  var _a22, _b;\n  if (timeout == null || typeof timeout === \"number\") {\n    return void 0;\n  }\n  return (_b = (_a22 = timeout.tools) == null ? void 0 : _a22[`${toolName}Ms`]) != null ? _b : timeout.toolMs;\n}\n\n// src/prompt/standardize-prompt.ts\nimport { InvalidPromptError as InvalidPromptError2 } from \"@ai-sdk/provider\";\nimport {\n  asArray as asArray2,\n  safeValidateTypes\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\n\n// src/prompt/message.ts\nimport { z as z4 } from \"zod/v4\";\n\n// src/types/provider-metadata.ts\nimport { z as z2 } from \"zod/v4\";\n\n// src/types/json-value.ts\nimport { z } from \"zod/v4\";\nvar jsonValueSchema = z.lazy(\n  () => z.union([\n    z.null(),\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.record(z.string(), jsonValueSchema.optional()),\n    z.array(jsonValueSchema)\n  ])\n);\n\n// src/types/provider-metadata.ts\nvar providerMetadataSchema = z2.record(\n  z2.string(),\n  z2.record(z2.string(), jsonValueSchema.optional())\n);\n\n// src/prompt/content-part.ts\nimport {\n  isBuffer as isBuffer2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\nvar fileInlineDataSchema = z3.union([\n  z3.string(),\n  z3.instanceof(Uint8Array),\n  z3.instanceof(ArrayBuffer),\n  z3.custom(isBuffer2, { message: \"Must be a Buffer\" })\n]);\nvar providerReferenceSchema = z3.record(z3.string(), z3.string());\nvar textPartSchema = z3.object({\n  type: z3.literal(\"text\"),\n  text: z3.string(),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar imagePartSchema = z3.object({\n  type: z3.literal(\"image\"),\n  image: z3.union([\n    fileInlineDataSchema,\n    z3.instanceof(URL),\n    providerReferenceSchema\n  ]),\n  mediaType: z3.string().optional(),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar taggedFileDataSchema = z3.discriminatedUnion(\"type\", [\n  z3.object({ type: z3.literal(\"data\"), data: fileInlineDataSchema }),\n  z3.object({ type: z3.literal(\"url\"), url: z3.instanceof(URL) }),\n  z3.object({\n    type: z3.literal(\"reference\"),\n    reference: providerReferenceSchema\n  }),\n  z3.object({ type: z3.literal(\"text\"), text: z3.string() })\n]);\nvar taggedReasoningFileDataSchema = z3.discriminatedUnion(\"type\", [\n  z3.object({ type: z3.literal(\"data\"), data: fileInlineDataSchema }),\n  z3.object({ type: z3.literal(\"url\"), url: z3.instanceof(URL) })\n]);\nvar filePartSchema = z3.object({\n  type: z3.literal(\"file\"),\n  data: z3.union([\n    taggedFileDataSchema,\n    fileInlineDataSchema,\n    z3.instanceof(URL),\n    providerReferenceSchema\n  ]),\n  filename: z3.string().optional(),\n  mediaType: z3.string(),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar reasoningPartSchema = z3.object({\n  type: z3.literal(\"reasoning\"),\n  text: z3.string(),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar customPartSchema = z3.object({\n  type: z3.literal(\"custom\"),\n  kind: z3.string().transform((value) => value),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar reasoningFilePartSchema = z3.object({\n  type: z3.literal(\"reasoning-file\"),\n  data: z3.union([\n    taggedReasoningFileDataSchema,\n    fileInlineDataSchema,\n    z3.instanceof(URL)\n  ]),\n  mediaType: z3.string(),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar toolCallPartSchema = z3.object({\n  type: z3.literal(\"tool-call\"),\n  toolCallId: z3.string(),\n  toolName: z3.string(),\n  input: z3.unknown(),\n  providerOptions: providerMetadataSchema.optional(),\n  providerExecuted: z3.boolean().optional()\n});\nvar outputSchema = z3.discriminatedUnion(\n  \"type\",\n  [\n    z3.object({\n      type: z3.literal(\"text\"),\n      value: z3.string(),\n      providerOptions: providerMetadataSchema.optional()\n    }),\n    z3.object({\n      type: z3.literal(\"json\"),\n      value: jsonValueSchema,\n      providerOptions: providerMetadataSchema.optional()\n    }),\n    z3.object({\n      type: z3.literal(\"execution-denied\"),\n      reason: z3.string().optional(),\n      providerOptions: providerMetadataSchema.optional()\n    }),\n    z3.object({\n      type: z3.literal(\"error-text\"),\n      value: z3.string(),\n      providerOptions: providerMetadataSchema.optional()\n    }),\n    z3.object({\n      type: z3.literal(\"error-json\"),\n      value: jsonValueSchema,\n      providerOptions: providerMetadataSchema.optional()\n    }),\n    z3.object({\n      type: z3.literal(\"content\"),\n      value: z3.array(\n        z3.union([\n          z3.object({\n            type: z3.literal(\"text\"),\n            text: z3.string(),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            type: z3.literal(\"file\"),\n            data: taggedFileDataSchema,\n            mediaType: z3.string(),\n            filename: z3.string().optional(),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"file-data\"),\n            data: z3.string(),\n            mediaType: z3.string(),\n            filename: z3.string().optional(),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"file-url\"),\n            url: z3.string(),\n            mediaType: z3.string().optional(),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"file-id\"),\n            fileId: z3.union([z3.string(), z3.record(z3.string(), z3.string())]),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"file-reference\"),\n            providerReference: z3.record(z3.string(), z3.string()),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"image-data\"),\n            data: z3.string(),\n            mediaType: z3.string(),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"image-url\"),\n            url: z3.string(),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"image-file-id\"),\n            fileId: z3.union([z3.string(), z3.record(z3.string(), z3.string())]),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            // Deprecated.\n            type: z3.literal(\"image-file-reference\"),\n            providerReference: z3.record(z3.string(), z3.string()),\n            providerOptions: providerMetadataSchema.optional()\n          }),\n          z3.object({\n            type: z3.literal(\"custom\"),\n            providerOptions: providerMetadataSchema.optional()\n          })\n        ])\n      )\n    })\n  ]\n);\nvar toolResultPartSchema = z3.object({\n  type: z3.literal(\"tool-result\"),\n  toolCallId: z3.string(),\n  toolName: z3.string(),\n  output: outputSchema,\n  providerOptions: providerMetadataSchema.optional()\n});\nvar toolApprovalRequestSchema = z3.object({\n  type: z3.literal(\"tool-approval-request\"),\n  approvalId: z3.string(),\n  toolCallId: z3.string()\n});\nvar toolApprovalResponseSchema = z3.object({\n  type: z3.literal(\"tool-approval-response\"),\n  approvalId: z3.string(),\n  approved: z3.boolean(),\n  reason: z3.string().optional()\n});\n\n// src/prompt/message.ts\nvar systemModelMessageSchema = z4.object(\n  {\n    role: z4.literal(\"system\"),\n    content: z4.string(),\n    providerOptions: providerMetadataSchema.optional()\n  }\n);\nvar userModelMessageSchema = z4.object({\n  role: z4.literal(\"user\"),\n  content: z4.union([\n    z4.string(),\n    z4.array(z4.union([textPartSchema, imagePartSchema, filePartSchema]))\n  ]),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar assistantModelMessageSchema = z4.object({\n  role: z4.literal(\"assistant\"),\n  content: z4.union([\n    z4.string(),\n    z4.array(\n      z4.union([\n        textPartSchema,\n        customPartSchema,\n        filePartSchema,\n        reasoningPartSchema,\n        reasoningFilePartSchema,\n        toolCallPartSchema,\n        toolResultPartSchema,\n        toolApprovalRequestSchema\n      ])\n    )\n  ]),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar toolModelMessageSchema = z4.object({\n  role: z4.literal(\"tool\"),\n  content: z4.array(z4.union([toolResultPartSchema, toolApprovalResponseSchema])),\n  providerOptions: providerMetadataSchema.optional()\n});\nvar modelMessageSchema = z4.union([\n  systemModelMessageSchema,\n  userModelMessageSchema,\n  assistantModelMessageSchema,\n  toolModelMessageSchema\n]);\n\n// src/prompt/standardize-prompt.ts\nasync function standardizePrompt({\n  allowSystemInMessages = false,\n  system,\n  instructions = system,\n  prompt,\n  messages\n}) {\n  if (prompt == null && messages == null) {\n    throw new InvalidPromptError2({\n      prompt,\n      message: \"prompt or messages must be defined\"\n    });\n  }\n  if (prompt != null && messages != null) {\n    throw new InvalidPromptError2({\n      prompt,\n      message: \"prompt and messages cannot be defined at the same time\"\n    });\n  }\n  if (typeof instructions !== \"string\" && !asArray2(instructions).every((message) => message.role === \"system\")) {\n    throw new InvalidPromptError2({\n      prompt,\n      message: \"instructions must be a string, SystemModelMessage, or array of SystemModelMessage\"\n    });\n  }\n  if (prompt != null && typeof prompt === \"string\") {\n    messages = [{ role: \"user\", content: prompt }];\n  } else if (prompt != null && Array.isArray(prompt)) {\n    messages = prompt;\n  } else if (messages == null) {\n    throw new InvalidPromptError2({\n      prompt,\n      message: \"prompt or messages must be defined\"\n    });\n  }\n  if (messages.length === 0) {\n    throw new InvalidPromptError2({\n      prompt,\n      message: \"messages must not be empty\"\n    });\n  }\n  if (!allowSystemInMessages && messages.some((message) => message.role === \"system\")) {\n    throw new InvalidPromptError2({\n      prompt,\n      message: \"System messages are not allowed in the prompt or messages fields. Use the instructions option instead.\"\n    });\n  }\n  const validationResult = await safeValidateTypes({\n    value: messages,\n    schema: z5.array(modelMessageSchema)\n  });\n  if (!validationResult.success) {\n    throw new InvalidPromptError2({\n      prompt,\n      message: \"The messages do not match the ModelMessage[] schema.\",\n      cause: validationResult.error\n    });\n  }\n  return { messages, instructions };\n}\n\n// src/prompt/wrap-gateway-error.ts\nimport { GatewayAuthenticationError } from \"@ai-sdk/gateway\";\nimport { AISDKError as AISDKError23 } from \"@ai-sdk/provider\";\nfunction wrapGatewayError(error) {\n  if (!GatewayAuthenticationError.isInstance(error))\n    return error;\n  const isProductionEnv = (process == null ? void 0 : process.env.NODE_ENV) === \"production\";\n  const moreInfoURL = \"https://ai-sdk.dev/unauthenticated-ai-gateway\";\n  if (isProductionEnv) {\n    return new AISDKError23({\n      name: \"GatewayError\",\n      message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`\n    });\n  }\n  return Object.assign(\n    new Error(`\\x1B[1m\\x1B[31mUnauthenticated request to AI Gateway.\\x1B[0m\n\nTo authenticate, set the \\x1B[33mAI_GATEWAY_API_KEY\\x1B[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\x1B[34m${moreInfoURL}\\x1B[0m\n\n`),\n    { name: \"GatewayAuthenticationError\" }\n  );\n}\n\n// src/types/usage.ts\nfunction asLanguageModelUsage(usage) {\n  return {\n    inputTokens: usage.inputTokens.total,\n    inputTokenDetails: {\n      noCacheTokens: usage.inputTokens.noCache,\n      cacheReadTokens: usage.inputTokens.cacheRead,\n      cacheWriteTokens: usage.inputTokens.cacheWrite\n    },\n    outputTokens: usage.outputTokens.total,\n    outputTokenDetails: {\n      textTokens: usage.outputTokens.text,\n      reasoningTokens: usage.outputTokens.reasoning\n    },\n    totalTokens: addTokenCounts(\n      usage.inputTokens.total,\n      usage.outputTokens.total\n    ),\n    raw: usage.raw\n  };\n}\nfunction createNullLanguageModelUsage() {\n  return {\n    inputTokens: void 0,\n    inputTokenDetails: {\n      noCacheTokens: void 0,\n      cacheReadTokens: void 0,\n      cacheWriteTokens: void 0\n    },\n    outputTokens: void 0,\n    outputTokenDetails: {\n      textTokens: void 0,\n      reasoningTokens: void 0\n    },\n    totalTokens: void 0,\n    raw: void 0\n  };\n}\nfunction addLanguageModelUsage(usage1, usage2) {\n  var _a22, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n  return {\n    inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n    inputTokenDetails: {\n      noCacheTokens: addTokenCounts(\n        (_a22 = usage1.inputTokenDetails) == null ? void 0 : _a22.noCacheTokens,\n        (_b = usage2.inputTokenDetails) == null ? void 0 : _b.noCacheTokens\n      ),\n      cacheReadTokens: addTokenCounts(\n        (_c = usage1.inputTokenDetails) == null ? void 0 : _c.cacheReadTokens,\n        (_d = usage2.inputTokenDetails) == null ? void 0 : _d.cacheReadTokens\n      ),\n      cacheWriteTokens: addTokenCounts(\n        (_e = usage1.inputTokenDetails) == null ? void 0 : _e.cacheWriteTokens,\n        (_f = usage2.inputTokenDetails) == null ? void 0 : _f.cacheWriteTokens\n      )\n    },\n    outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n    outputTokenDetails: {\n      textTokens: addTokenCounts(\n        (_g = usage1.outputTokenDetails) == null ? void 0 : _g.textTokens,\n        (_h = usage2.outputTokenDetails) == null ? void 0 : _h.textTokens\n      ),\n      reasoningTokens: addTokenCounts(\n        (_i = usage1.outputTokenDetails) == null ? void 0 : _i.reasoningTokens,\n        (_j = usage2.outputTokenDetails) == null ? void 0 : _j.reasoningTokens\n      )\n    },\n    totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)\n  };\n}\nfunction addTokenCounts(tokenCount1, tokenCount2) {\n  return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);\n}\nfunction addImageModelUsage(usage1, usage2) {\n  return {\n    inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n    outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n    totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)\n  };\n}\n\n// src/util/merge-abort-signals.ts\nimport { filterNullable } from \"@ai-sdk/provider-utils\";\nfunction mergeAbortSignals(...signals) {\n  const validSignals = filterNullable(...signals).map(\n    (signal) => signal instanceof AbortSignal ? signal : AbortSignal.timeout(signal)\n  );\n  return validSignals.length === 0 ? void 0 : validSignals.length === 1 ? validSignals[0] : AbortSignal.any(validSignals);\n}\n\n// src/util/merge-objects.ts\nfunction mergeObjects(base, overrides) {\n  if (base === void 0 && overrides === void 0) {\n    return void 0;\n  }\n  if (base === void 0) {\n    return overrides;\n  }\n  if (overrides === void 0) {\n    return base;\n  }\n  const result = { ...base };\n  for (const key in overrides) {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n      continue;\n    }\n    if (Object.prototype.hasOwnProperty.call(overrides, key)) {\n      const overridesValue = overrides[key];\n      if (overridesValue === void 0)\n        continue;\n      const baseValue = key in base ? base[key] : void 0;\n      const isSourceObject = overridesValue !== null && typeof overridesValue === \"object\" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);\n      const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === \"object\" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);\n      if (isSourceObject && isTargetObject) {\n        result[key] = mergeObjects(\n          baseValue,\n          overridesValue\n        );\n      } else {\n        result[key] = overridesValue;\n      }\n    }\n  }\n  return result;\n}\n\n// src/util/now.ts\nfunction now() {\n  var _a22, _b;\n  return (_b = (_a22 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a22.now()) != null ? _b : Date.now();\n}\n\n// src/util/notify.ts\nimport { asArray as asArray3 } from \"@ai-sdk/provider-utils\";\nasync function notify(options) {\n  await Promise.all(\n    asArray3(options.callbacks).map(async (callback) => {\n      try {\n        await (callback == null ? void 0 : callback(options.event));\n      } catch (e) {\n      }\n    })\n  );\n}\n\n// src/util/retry-with-exponential-backoff.ts\nimport { APICallError as APICallError2 } from \"@ai-sdk/provider\";\nimport { GatewayError } from \"@ai-sdk/gateway\";\nimport { delay, getErrorMessage as getErrorMessage4, isAbortError } from \"@ai-sdk/provider-utils\";\nfunction getRetryDelayInMs({\n  error,\n  exponentialBackoffDelay\n}) {\n  const headers = APICallError2.isInstance(error) ? error.responseHeaders : APICallError2.isInstance(error.cause) ? error.cause.responseHeaders : void 0;\n  if (!headers)\n    return exponentialBackoffDelay;\n  let ms;\n  const retryAfterMs = headers[\"retry-after-ms\"];\n  if (retryAfterMs) {\n    const timeoutMs = parseFloat(retryAfterMs);\n    if (!Number.isNaN(timeoutMs)) {\n      ms = timeoutMs;\n    }\n  }\n  const retryAfter = headers[\"retry-after\"];\n  if (retryAfter && ms === void 0) {\n    const timeoutSeconds = parseFloat(retryAfter);\n    if (!Number.isNaN(timeoutSeconds)) {\n      ms = timeoutSeconds * 1e3;\n    } else {\n      ms = Date.parse(retryAfter) - Date.now();\n    }\n  }\n  if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) {\n    return ms;\n  }\n  return exponentialBackoffDelay;\n}\nvar retryWithExponentialBackoffRespectingRetryHeaders = ({\n  maxRetries = 2,\n  initialDelayInMs = 2e3,\n  backoffFactor = 2,\n  abortSignal\n} = {}) => async (f) => _retryWithExponentialBackoff(f, {\n  maxRetries,\n  delayInMs: initialDelayInMs,\n  backoffFactor,\n  abortSignal\n});\nasync function _retryWithExponentialBackoff(f, {\n  maxRetries,\n  delayInMs,\n  backoffFactor,\n  abortSignal\n}, errors = []) {\n  try {\n    return await f();\n  } catch (error) {\n    if (isAbortError(error)) {\n      throw error;\n    }\n    if (maxRetries === 0) {\n      throw error;\n    }\n    const errorMessage = getErrorMessage4(error);\n    const newErrors = [...errors, error];\n    const tryNumber = newErrors.length;\n    if (tryNumber > maxRetries) {\n      throw new RetryError({\n        message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n        reason: \"maxRetriesExceeded\",\n        errors: newErrors\n      });\n    }\n    if (error instanceof Error && (APICallError2.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true) && tryNumber <= maxRetries) {\n      await delay(\n        getRetryDelayInMs({\n          error,\n          exponentialBackoffDelay: delayInMs\n        }),\n        { abortSignal }\n      );\n      return _retryWithExponentialBackoff(\n        f,\n        {\n          maxRetries,\n          delayInMs: backoffFactor * delayInMs,\n          backoffFactor,\n          abortSignal\n        },\n        newErrors\n      );\n    }\n    if (tryNumber === 1) {\n      throw error;\n    }\n    throw new RetryError({\n      message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n      reason: \"errorNotRetryable\",\n      errors: newErrors\n    });\n  }\n}\n\n// src/util/prepare-retries.ts\nfunction prepareRetries({\n  maxRetries,\n  abortSignal\n}) {\n  if (maxRetries != null) {\n    if (!Number.isInteger(maxRetries)) {\n      throw new InvalidArgumentError({\n        parameter: \"maxRetries\",\n        value: maxRetries,\n        message: \"maxRetries must be an integer\"\n      });\n    }\n    if (maxRetries < 0) {\n      throw new InvalidArgumentError({\n        parameter: \"maxRetries\",\n        value: maxRetries,\n        message: \"maxRetries must be >= 0\"\n      });\n    }\n  }\n  const maxRetriesResult = maxRetries != null ? maxRetries : 2;\n  return {\n    maxRetries: maxRetriesResult,\n    retry: retryWithExponentialBackoffRespectingRetryHeaders({\n      maxRetries: maxRetriesResult,\n      abortSignal\n    })\n  };\n}\n\n// src/util/set-abort-timeout.ts\nfunction setAbortTimeout({\n  abortController,\n  label,\n  timeoutMs\n}) {\n  if (abortController == null || timeoutMs == null) {\n    return void 0;\n  }\n  return setTimeout(\n    () => abortController.abort(\n      new DOMException(\n        `${label} timeout of ${timeoutMs}ms exceeded`,\n        \"TimeoutError\"\n      )\n    ),\n    timeoutMs\n  );\n}\n\n// src/generate-text/calculate-tokens-per-second.ts\nfunction calculateTokensPerSecond({\n  tokens,\n  durationMs\n}) {\n  const tokenRate = 1e3 * (tokens != null ? tokens : 0) / (durationMs != null ? durationMs : 0);\n  return Number.isFinite(tokenRate) ? tokenRate : 0;\n}\n\n// src/generate-text/collect-tool-approvals.ts\nfunction collectToolApprovals({\n  messages\n}) {\n  const lastMessage = messages.at(-1);\n  if ((lastMessage == null ? void 0 : lastMessage.role) != \"tool\") {\n    return {\n      approvedToolApprovals: [],\n      deniedToolApprovals: []\n    };\n  }\n  const toolCallsByToolCallId = {};\n  for (const message of messages) {\n    if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n      const content = message.content;\n      for (const part of content) {\n        if (part.type === \"tool-call\") {\n          toolCallsByToolCallId[part.toolCallId] = part;\n        }\n      }\n    }\n  }\n  const toolApprovalRequestsByApprovalId = {};\n  for (const message of messages) {\n    if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n      const content = message.content;\n      for (const part of content) {\n        if (part.type === \"tool-approval-request\") {\n          toolApprovalRequestsByApprovalId[part.approvalId] = part;\n        }\n      }\n    }\n  }\n  const toolResults = {};\n  for (const part of lastMessage.content) {\n    if (part.type === \"tool-result\") {\n      toolResults[part.toolCallId] = part;\n    }\n  }\n  const approvedToolApprovals = [];\n  const deniedToolApprovals = [];\n  const approvalResponses = lastMessage.content.filter(\n    (part) => part.type === \"tool-approval-response\"\n  );\n  for (const approvalResponse of approvalResponses) {\n    const approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n    if (approvalRequest == null) {\n      throw new InvalidToolApprovalError({\n        approvalId: approvalResponse.approvalId\n      });\n    }\n    if (toolResults[approvalRequest.toolCallId] != null) {\n      continue;\n    }\n    const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n    if (toolCall == null) {\n      throw new ToolCallNotFoundForApprovalError({\n        toolCallId: approvalRequest.toolCallId,\n        approvalId: approvalRequest.approvalId\n      });\n    }\n    const approval = {\n      approvalRequest,\n      approvalResponse,\n      toolCall\n    };\n    if (approvalResponse.approved) {\n      approvedToolApprovals.push(approval);\n    } else {\n      deniedToolApprovals.push(approval);\n    }\n  }\n  return { approvedToolApprovals, deniedToolApprovals };\n}\n\n// src/generate-text/execute-tool-call.ts\nimport {\n  executeTool,\n  isExecutableTool\n} from \"@ai-sdk/provider-utils\";\n\n// src/generate-text/validate-tool-context.ts\nimport { validateTypes } from \"@ai-sdk/provider-utils\";\nasync function validateToolContext({\n  toolName,\n  context,\n  contextSchema\n}) {\n  if (contextSchema == null) {\n    return context;\n  }\n  return await validateTypes({\n    value: context,\n    schema: contextSchema,\n    context: {\n      field: \"tool context\",\n      entityName: toolName\n    }\n  });\n}\n\n// src/generate-text/execute-tool-call.ts\nasync function executeToolCall({\n  toolCall,\n  tools,\n  toolsContext,\n  callId,\n  messages,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  onPreliminaryToolResult,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  executeToolInTelemetryContext = async ({ execute }) => await execute(),\n  runInTracingChannelSpan = async ({ execute }) => await execute()\n}) {\n  const { toolName, toolCallId, input } = toolCall;\n  const tool2 = tools == null ? void 0 : tools[toolName];\n  if (!isExecutableTool(tool2)) {\n    return void 0;\n  }\n  const context = await validateToolContext({\n    toolName,\n    context: toolsContext == null ? void 0 : toolsContext[toolName],\n    contextSchema: tool2.contextSchema\n  });\n  const toolExecutionContext = {\n    toolCall,\n    messages,\n    toolContext: context\n  };\n  const baseCallbackEvent = {\n    callId,\n    ...toolExecutionContext\n  };\n  return await runInTracingChannelSpan({\n    type: \"executeTool\",\n    event: baseCallbackEvent,\n    execute: async () => {\n      let output;\n      await notify({\n        event: baseCallbackEvent,\n        callbacks: onToolExecutionStart\n      });\n      const toolTimeoutMs = getToolTimeoutMs(timeout, toolName);\n      const toolAbortSignal = mergeAbortSignals(abortSignal, toolTimeoutMs);\n      let toolExecutionMs = 0;\n      try {\n        await executeToolInTelemetryContext({\n          callId,\n          toolCallId,\n          ...toolExecutionContext,\n          execute: async () => {\n            const startTime = now();\n            try {\n              const stream = executeTool({\n                tool: tool2,\n                input,\n                options: {\n                  toolCallId,\n                  messages,\n                  abortSignal: toolAbortSignal,\n                  context,\n                  experimental_sandbox: sandbox\n                }\n              });\n              for await (const part of stream) {\n                if (part.type === \"preliminary\") {\n                  onPreliminaryToolResult == null ? void 0 : onPreliminaryToolResult({\n                    ...toolCall,\n                    type: \"tool-result\",\n                    output: part.output,\n                    preliminary: true\n                  });\n                } else {\n                  output = part.output;\n                }\n              }\n            } finally {\n              toolExecutionMs = now() - startTime;\n            }\n          }\n        });\n      } catch (error) {\n        const toolError = {\n          type: \"tool-error\",\n          toolCallId,\n          toolName,\n          input,\n          error,\n          dynamic: tool2.type === \"dynamic\",\n          ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {},\n          ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n        };\n        await notify({\n          event: {\n            ...baseCallbackEvent,\n            toolOutput: toolError,\n            toolExecutionMs\n          },\n          callbacks: onToolExecutionEnd\n        });\n        return {\n          output: toolError,\n          toolExecutionMs\n        };\n      }\n      const toolResult = {\n        type: \"tool-result\",\n        toolCallId,\n        toolName,\n        input,\n        output,\n        dynamic: tool2.type === \"dynamic\",\n        ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {},\n        ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n      };\n      await notify({\n        event: {\n          ...baseCallbackEvent,\n          toolOutput: toolResult,\n          toolExecutionMs\n        },\n        callbacks: onToolExecutionEnd\n      });\n      return {\n        output: toolResult,\n        toolExecutionMs\n      };\n    }\n  });\n}\n\n// src/generate-text/filter-active-tools.ts\nfunction filterActiveTools({\n  tools,\n  activeTools\n}) {\n  if (tools == null || activeTools == null) {\n    return tools;\n  }\n  return Object.fromEntries(\n    Object.entries(tools).filter(([name22]) => activeTools.includes(name22))\n  );\n}\n\n// src/generate-text/generated-file.ts\nimport {\n  convertBase64ToUint8Array,\n  convertUint8ArrayToBase64\n} from \"@ai-sdk/provider-utils\";\nvar DefaultGeneratedFile = class {\n  constructor({\n    data,\n    mediaType\n  }) {\n    const isUint8Array = data instanceof Uint8Array;\n    this.base64Data = isUint8Array ? void 0 : data;\n    this.uint8ArrayData = isUint8Array ? data : void 0;\n    this.mediaType = mediaType;\n  }\n  // lazy conversion with caching to avoid unnecessary conversion overhead:\n  get base64() {\n    if (this.base64Data == null) {\n      this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);\n    }\n    return this.base64Data;\n  }\n  // lazy conversion with caching to avoid unnecessary conversion overhead:\n  get uint8Array() {\n    if (this.uint8ArrayData == null) {\n      this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);\n    }\n    return this.uint8ArrayData;\n  }\n};\nvar DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {\n  constructor(options) {\n    super(options);\n    this.type = \"file\";\n  }\n};\n\n// src/generate-text/output.ts\nvar output_exports = {};\n__export(output_exports, {\n  array: () => array,\n  choice: () => choice,\n  json: () => json,\n  object: () => object,\n  text: () => text\n});\nimport {\n  TypeValidationError as TypeValidationError2\n} from \"@ai-sdk/provider\";\nimport {\n  asSchema as asSchema2,\n  resolve,\n  safeParseJSON as safeParseJSON2,\n  safeValidateTypes as safeValidateTypes2\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/parse-partial-json.ts\nimport { safeParseJSON } from \"@ai-sdk/provider-utils\";\n\n// src/util/fix-json.ts\nfunction fixJson(input) {\n  const stack = [\"ROOT\"];\n  let lastValidIndex = -1;\n  let literalStart = null;\n  let unicodeEscapeDigits = 0;\n  function isHexDigit(char) {\n    return char >= \"0\" && char <= \"9\" || char >= \"A\" && char <= \"F\" || char >= \"a\" && char <= \"f\";\n  }\n  function processValueStart(char, i, swapState) {\n    {\n      switch (char) {\n        case '\"': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push(\"INSIDE_STRING\");\n          break;\n        }\n        case \"f\":\n        case \"t\":\n        case \"n\": {\n          lastValidIndex = i;\n          literalStart = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push(\"INSIDE_LITERAL\");\n          break;\n        }\n        case \"-\": {\n          stack.pop();\n          stack.push(swapState);\n          stack.push(\"INSIDE_NUMBER\");\n          break;\n        }\n        case \"0\":\n        case \"1\":\n        case \"2\":\n        case \"3\":\n        case \"4\":\n        case \"5\":\n        case \"6\":\n        case \"7\":\n        case \"8\":\n        case \"9\": {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push(\"INSIDE_NUMBER\");\n          break;\n        }\n        case \"{\": {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push(\"INSIDE_OBJECT_START\");\n          break;\n        }\n        case \"[\": {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push(\"INSIDE_ARRAY_START\");\n          break;\n        }\n      }\n    }\n  }\n  function processAfterObjectValue(char, i) {\n    switch (char) {\n      case \",\": {\n        stack.pop();\n        stack.push(\"INSIDE_OBJECT_AFTER_COMMA\");\n        break;\n      }\n      case \"}\": {\n        lastValidIndex = i;\n        stack.pop();\n        break;\n      }\n    }\n  }\n  function processAfterArrayValue(char, i) {\n    switch (char) {\n      case \",\": {\n        stack.pop();\n        stack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n        break;\n      }\n      case \"]\": {\n        lastValidIndex = i;\n        stack.pop();\n        break;\n      }\n    }\n  }\n  for (let i = 0; i < input.length; i++) {\n    const char = input[i];\n    const currentState = stack[stack.length - 1];\n    switch (currentState) {\n      case \"ROOT\":\n        processValueStart(char, i, \"FINISH\");\n        break;\n      case \"INSIDE_OBJECT_START\": {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push(\"INSIDE_OBJECT_KEY\");\n            break;\n          }\n          case \"}\": {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_OBJECT_AFTER_COMMA\": {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push(\"INSIDE_OBJECT_KEY\");\n            break;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_OBJECT_KEY\": {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push(\"INSIDE_OBJECT_AFTER_KEY\");\n            break;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_OBJECT_AFTER_KEY\": {\n        switch (char) {\n          case \":\": {\n            stack.pop();\n            stack.push(\"INSIDE_OBJECT_BEFORE_VALUE\");\n            break;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_OBJECT_BEFORE_VALUE\": {\n        processValueStart(char, i, \"INSIDE_OBJECT_AFTER_VALUE\");\n        break;\n      }\n      case \"INSIDE_OBJECT_AFTER_VALUE\": {\n        processAfterObjectValue(char, i);\n        break;\n      }\n      case \"INSIDE_STRING\": {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            lastValidIndex = i;\n            break;\n          }\n          case \"\\\\\": {\n            stack.push(\"INSIDE_STRING_ESCAPE\");\n            break;\n          }\n          default: {\n            lastValidIndex = i;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_ARRAY_START\": {\n        switch (char) {\n          case \"]\": {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n          default: {\n            lastValidIndex = i;\n            processValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n            break;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_ARRAY_AFTER_VALUE\": {\n        switch (char) {\n          case \",\": {\n            stack.pop();\n            stack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n            break;\n          }\n          case \"]\": {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n          default: {\n            lastValidIndex = i;\n            break;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_ARRAY_AFTER_COMMA\": {\n        processValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n        break;\n      }\n      case \"INSIDE_STRING_ESCAPE\": {\n        stack.pop();\n        if (char === \"u\") {\n          unicodeEscapeDigits = 0;\n          stack.push(\"INSIDE_STRING_UNICODE_ESCAPE\");\n        } else {\n          lastValidIndex = i;\n        }\n        break;\n      }\n      case \"INSIDE_STRING_UNICODE_ESCAPE\": {\n        if (isHexDigit(char)) {\n          unicodeEscapeDigits++;\n          if (unicodeEscapeDigits === 4) {\n            stack.pop();\n            lastValidIndex = i;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_NUMBER\": {\n        switch (char) {\n          case \"0\":\n          case \"1\":\n          case \"2\":\n          case \"3\":\n          case \"4\":\n          case \"5\":\n          case \"6\":\n          case \"7\":\n          case \"8\":\n          case \"9\": {\n            lastValidIndex = i;\n            break;\n          }\n          case \"e\":\n          case \"E\":\n          case \"-\":\n          case \".\": {\n            break;\n          }\n          case \",\": {\n            stack.pop();\n            if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") {\n              processAfterArrayValue(char, i);\n            }\n            if (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") {\n              processAfterObjectValue(char, i);\n            }\n            break;\n          }\n          case \"}\": {\n            stack.pop();\n            if (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") {\n              processAfterObjectValue(char, i);\n            }\n            break;\n          }\n          case \"]\": {\n            stack.pop();\n            if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") {\n              processAfterArrayValue(char, i);\n            }\n            break;\n          }\n          default: {\n            stack.pop();\n            break;\n          }\n        }\n        break;\n      }\n      case \"INSIDE_LITERAL\": {\n        const partialLiteral = input.substring(literalStart, i + 1);\n        if (!\"false\".startsWith(partialLiteral) && !\"true\".startsWith(partialLiteral) && !\"null\".startsWith(partialLiteral)) {\n          stack.pop();\n          if (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") {\n            processAfterObjectValue(char, i);\n          } else if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") {\n            processAfterArrayValue(char, i);\n          }\n        } else {\n          lastValidIndex = i;\n        }\n        break;\n      }\n    }\n  }\n  let result = input.slice(0, lastValidIndex + 1);\n  for (let i = stack.length - 1; i >= 0; i--) {\n    const state = stack[i];\n    switch (state) {\n      case \"INSIDE_STRING\": {\n        result += '\"';\n        break;\n      }\n      case \"INSIDE_OBJECT_KEY\":\n      case \"INSIDE_OBJECT_AFTER_KEY\":\n      case \"INSIDE_OBJECT_AFTER_COMMA\":\n      case \"INSIDE_OBJECT_START\":\n      case \"INSIDE_OBJECT_BEFORE_VALUE\":\n      case \"INSIDE_OBJECT_AFTER_VALUE\": {\n        result += \"}\";\n        break;\n      }\n      case \"INSIDE_ARRAY_START\":\n      case \"INSIDE_ARRAY_AFTER_COMMA\":\n      case \"INSIDE_ARRAY_AFTER_VALUE\": {\n        result += \"]\";\n        break;\n      }\n      case \"INSIDE_LITERAL\": {\n        const partialLiteral = input.substring(literalStart, input.length);\n        if (\"true\".startsWith(partialLiteral)) {\n          result += \"true\".slice(partialLiteral.length);\n        } else if (\"false\".startsWith(partialLiteral)) {\n          result += \"false\".slice(partialLiteral.length);\n        } else if (\"null\".startsWith(partialLiteral)) {\n          result += \"null\".slice(partialLiteral.length);\n        }\n      }\n    }\n  }\n  return result;\n}\n\n// src/util/parse-partial-json.ts\nasync function parsePartialJson(jsonText) {\n  if (jsonText === void 0) {\n    return { value: void 0, state: \"undefined-input\" };\n  }\n  let result = await safeParseJSON({ text: jsonText });\n  if (result.success) {\n    return { value: result.value, state: \"successful-parse\" };\n  }\n  result = await safeParseJSON({ text: fixJson(jsonText) });\n  if (result.success) {\n    return { value: result.value, state: \"repaired-parse\" };\n  }\n  return { value: void 0, state: \"failed-parse\" };\n}\n\n// src/generate-text/output.ts\nvar text = () => ({\n  name: \"text\",\n  responseFormat: Promise.resolve({ type: \"text\" }),\n  async parseCompleteOutput({ text: text2 }) {\n    return text2;\n  },\n  async parsePartialOutput({ text: text2 }) {\n    return { partial: text2 };\n  },\n  createElementStreamTransform() {\n    return void 0;\n  }\n});\nvar object = ({\n  schema: inputSchema,\n  name: name22,\n  description\n}) => {\n  const schema = asSchema2(inputSchema);\n  return {\n    name: \"object\",\n    responseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({\n      type: \"json\",\n      schema: jsonSchema2,\n      ...name22 != null && { name: name22 },\n      ...description != null && { description }\n    })),\n    async parseCompleteOutput({ text: text2 }, context) {\n      const parseResult = await safeParseJSON2({ text: text2 });\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: \"No object generated: could not parse the response.\",\n          cause: parseResult.error,\n          text: text2,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason\n        });\n      }\n      const validationResult = await safeValidateTypes2({\n        value: parseResult.value,\n        schema\n      });\n      if (!validationResult.success) {\n        throw new NoObjectGeneratedError({\n          message: \"No object generated: response did not match schema.\",\n          cause: validationResult.error,\n          text: text2,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason\n        });\n      }\n      return validationResult.value;\n    },\n    async parsePartialOutput({ text: text2 }) {\n      const result = await parsePartialJson(text2);\n      switch (result.state) {\n        case \"failed-parse\":\n        case \"undefined-input\": {\n          return void 0;\n        }\n        case \"repaired-parse\":\n        case \"successful-parse\": {\n          return {\n            // Note: currently no validation of partial results:\n            partial: result.value\n          };\n        }\n      }\n    },\n    createElementStreamTransform() {\n      return void 0;\n    }\n  };\n};\nvar array = ({\n  element: inputElementSchema,\n  name: name22,\n  description\n}) => {\n  const elementSchema = asSchema2(inputElementSchema);\n  return {\n    name: \"array\",\n    // JSON schema that describes an array of elements:\n    responseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema2) => {\n      const { $schema: _$schema, ...itemSchema } = jsonSchema2;\n      return {\n        type: \"json\",\n        schema: {\n          $schema: \"http://json-schema.org/draft-07/schema#\",\n          type: \"object\",\n          properties: {\n            elements: { type: \"array\", items: itemSchema }\n          },\n          required: [\"elements\"],\n          additionalProperties: false\n        },\n        ...name22 != null && { name: name22 },\n        ...description != null && { description }\n      };\n    }),\n    async parseCompleteOutput({ text: text2 }, context) {\n      const parseResult = await safeParseJSON2({ text: text2 });\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: \"No object generated: could not parse the response.\",\n          cause: parseResult.error,\n          text: text2,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason\n        });\n      }\n      const outerValue = parseResult.value;\n      if (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) {\n        throw new NoObjectGeneratedError({\n          message: \"No object generated: response did not match schema.\",\n          cause: new TypeValidationError2({\n            value: outerValue,\n            cause: \"response must be an object with an elements array\"\n          }),\n          text: text2,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason\n        });\n      }\n      const validatedElements = [];\n      for (const element of outerValue.elements) {\n        const validationResult = await safeValidateTypes2({\n          value: element,\n          schema: elementSchema\n        });\n        if (!validationResult.success) {\n          throw new NoObjectGeneratedError({\n            message: \"No object generated: response did not match schema.\",\n            cause: validationResult.error,\n            text: text2,\n            response: context.response,\n            usage: context.usage,\n            finishReason: context.finishReason\n          });\n        }\n        validatedElements.push(validationResult.value);\n      }\n      return validatedElements;\n    },\n    async parsePartialOutput({ text: text2 }) {\n      const result = await parsePartialJson(text2);\n      switch (result.state) {\n        case \"failed-parse\":\n        case \"undefined-input\": {\n          return void 0;\n        }\n        case \"repaired-parse\":\n        case \"successful-parse\": {\n          const outerValue = result.value;\n          if (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) {\n            return void 0;\n          }\n          const rawElements = result.state === \"repaired-parse\" && outerValue.elements.length > 0 ? outerValue.elements.slice(0, -1) : outerValue.elements;\n          const parsedElements = [];\n          for (const rawElement of rawElements) {\n            const validationResult = await safeValidateTypes2({\n              value: rawElement,\n              schema: elementSchema\n            });\n            if (validationResult.success) {\n              parsedElements.push(validationResult.value);\n            }\n          }\n          return { partial: parsedElements };\n        }\n      }\n    },\n    createElementStreamTransform() {\n      let publishedElements = 0;\n      return new TransformStream({\n        transform({ partialOutput }, controller) {\n          if (partialOutput != null) {\n            for (; publishedElements < partialOutput.length; publishedElements++) {\n              controller.enqueue(partialOutput[publishedElements]);\n            }\n          }\n        }\n      });\n    }\n  };\n};\nvar choice = ({\n  options: choiceOptions,\n  name: name22,\n  description\n}) => {\n  return {\n    name: \"choice\",\n    // JSON schema that describes an enumeration:\n    responseFormat: Promise.resolve({\n      type: \"json\",\n      schema: {\n        $schema: \"http://json-schema.org/draft-07/schema#\",\n        type: \"object\",\n        properties: {\n          result: { type: \"string\", enum: choiceOptions }\n        },\n        required: [\"result\"],\n        additionalProperties: false\n      },\n      ...name22 != null && { name: name22 },\n      ...description != null && { description }\n    }),\n    async parseCompleteOutput({ text: text2 }, context) {\n      const parseResult = await safeParseJSON2({ text: text2 });\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: \"No object generated: could not parse the response.\",\n          cause: parseResult.error,\n          text: text2,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason\n        });\n      }\n      const outerValue = parseResult.value;\n      if (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\" || !choiceOptions.includes(outerValue.result)) {\n        throw new NoObjectGeneratedError({\n          message: \"No object generated: response did not match schema.\",\n          cause: new TypeValidationError2({\n            value: outerValue,\n            cause: \"response must be an object that contains a choice value.\"\n          }),\n          text: text2,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason\n        });\n      }\n      return outerValue.result;\n    },\n    async parsePartialOutput({ text: text2 }) {\n      const result = await parsePartialJson(text2);\n      switch (result.state) {\n        case \"failed-parse\":\n        case \"undefined-input\": {\n          return void 0;\n        }\n        case \"repaired-parse\":\n        case \"successful-parse\": {\n          const outerValue = result.value;\n          if (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\") {\n            return void 0;\n          }\n          const potentialMatches = choiceOptions.filter(\n            (choiceOption) => choiceOption.startsWith(outerValue.result)\n          );\n          if (result.state === \"successful-parse\") {\n            return potentialMatches.includes(outerValue.result) ? { partial: outerValue.result } : void 0;\n          } else {\n            return potentialMatches.length === 1 ? { partial: potentialMatches[0] } : void 0;\n          }\n        }\n      }\n    },\n    createElementStreamTransform() {\n      return void 0;\n    }\n  };\n};\nvar json = ({\n  name: name22,\n  description\n} = {}) => {\n  return {\n    name: \"json\",\n    responseFormat: Promise.resolve({\n      type: \"json\",\n      ...name22 != null && { name: name22 },\n      ...description != null && { description }\n    }),\n    async parseCompleteOutput({ text: text2 }, context) {\n      const parseResult = await safeParseJSON2({ text: text2 });\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: \"No object generated: could not parse the response.\",\n          cause: parseResult.error,\n          text: text2,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason\n        });\n      }\n      return parseResult.value;\n    },\n    async parsePartialOutput({ text: text2 }) {\n      const result = await parsePartialJson(text2);\n      switch (result.state) {\n        case \"failed-parse\":\n        case \"undefined-input\": {\n          return void 0;\n        }\n        case \"repaired-parse\":\n        case \"successful-parse\": {\n          return result.value === void 0 ? void 0 : { partial: result.value };\n        }\n      }\n    },\n    createElementStreamTransform() {\n      return void 0;\n    }\n  };\n};\n\n// src/generate-text/parse-tool-call.ts\nimport {\n  asSchema as asSchema3,\n  safeParseJSON as safeParseJSON3,\n  safeValidateTypes as safeValidateTypes3\n} from \"@ai-sdk/provider-utils\";\nasync function parseToolCall({\n  toolCall,\n  tools,\n  repairToolCall,\n  refineToolInput,\n  messages,\n  instructions\n}) {\n  try {\n    if (tools == null) {\n      if (toolCall.providerExecuted && toolCall.dynamic) {\n        return await refineParsedToolCallInput({\n          toolCall: await parseProviderExecutedDynamicToolCall(toolCall),\n          refineToolInput\n        });\n      }\n      throw new NoSuchToolError({ toolName: toolCall.toolName });\n    }\n    try {\n      return await refineParsedToolCallInput({\n        toolCall: await doParseToolCall({ toolCall, tools }),\n        refineToolInput\n      });\n    } catch (error) {\n      if (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) {\n        throw error;\n      }\n      let repairedToolCall = null;\n      try {\n        repairedToolCall = await repairToolCall({\n          toolCall,\n          tools,\n          inputSchema: async ({ toolName }) => {\n            const { inputSchema } = tools[toolName];\n            return await asSchema3(inputSchema).jsonSchema;\n          },\n          instructions,\n          system: instructions,\n          messages,\n          error\n        });\n      } catch (repairError) {\n        throw new ToolCallRepairError({\n          cause: repairError,\n          originalError: error\n        });\n      }\n      if (repairedToolCall == null) {\n        throw error;\n      }\n      return await refineParsedToolCallInput({\n        toolCall: await doParseToolCall({ toolCall: repairedToolCall, tools }),\n        refineToolInput\n      });\n    }\n  } catch (error) {\n    const parsedInput = await safeParseJSON3({ text: toolCall.input });\n    const input = parsedInput.success ? parsedInput.value : toolCall.input;\n    const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n    return {\n      type: \"tool-call\",\n      toolCallId: toolCall.toolCallId,\n      toolName: toolCall.toolName,\n      input,\n      dynamic: true,\n      invalid: true,\n      error,\n      title: tool2 == null ? void 0 : tool2.title,\n      providerExecuted: toolCall.providerExecuted,\n      providerMetadata: toolCall.providerMetadata,\n      ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}\n    };\n  }\n}\nasync function refineParsedToolCallInput({\n  toolCall,\n  refineToolInput\n}) {\n  const refine = refineToolInput == null ? void 0 : refineToolInput[toolCall.toolName];\n  if (refine == null) {\n    return toolCall;\n  }\n  return {\n    ...toolCall,\n    input: await refine(toolCall.input)\n  };\n}\nasync function parseProviderExecutedDynamicToolCall(toolCall) {\n  const parseResult = toolCall.input.trim() === \"\" ? { success: true, value: {} } : await safeParseJSON3({ text: toolCall.input });\n  if (parseResult.success === false) {\n    throw new InvalidToolInputError({\n      toolName: toolCall.toolName,\n      toolInput: toolCall.input,\n      cause: parseResult.error\n    });\n  }\n  return {\n    type: \"tool-call\",\n    toolCallId: toolCall.toolCallId,\n    toolName: toolCall.toolName,\n    input: parseResult.value,\n    providerExecuted: true,\n    dynamic: true,\n    providerMetadata: toolCall.providerMetadata\n  };\n}\nasync function doParseToolCall({\n  toolCall,\n  tools\n}) {\n  const toolName = toolCall.toolName;\n  const tool2 = tools[toolName];\n  if (tool2 == null) {\n    if (toolCall.providerExecuted && toolCall.dynamic) {\n      return await parseProviderExecutedDynamicToolCall(toolCall);\n    }\n    throw new NoSuchToolError({\n      toolName: toolCall.toolName,\n      availableTools: Object.keys(tools)\n    });\n  }\n  const schema = asSchema3(tool2.inputSchema);\n  const parseResult = toolCall.input.trim() === \"\" ? await safeValidateTypes3({ value: {}, schema }) : await safeParseJSON3({ text: toolCall.input, schema });\n  if (parseResult.success === false) {\n    throw new InvalidToolInputError({\n      toolName,\n      toolInput: toolCall.input,\n      cause: parseResult.error\n    });\n  }\n  return tool2.type === \"dynamic\" ? {\n    type: \"tool-call\",\n    toolCallId: toolCall.toolCallId,\n    toolName: toolCall.toolName,\n    input: parseResult.value,\n    providerExecuted: toolCall.providerExecuted,\n    providerMetadata: toolCall.providerMetadata,\n    ...tool2.metadata != null ? { toolMetadata: tool2.metadata } : {},\n    dynamic: true,\n    title: tool2.title\n  } : {\n    type: \"tool-call\",\n    toolCallId: toolCall.toolCallId,\n    toolName,\n    input: parseResult.value,\n    providerExecuted: toolCall.providerExecuted,\n    providerMetadata: toolCall.providerMetadata,\n    ...tool2.metadata != null ? { toolMetadata: tool2.metadata } : {},\n    title: tool2.title\n  };\n}\n\n// src/generate-text/reasoning-output.ts\nfunction unwrapReasoningFileData(data) {\n  if (typeof data === \"object\" && data !== null && \"type\" in data) {\n    return data.type === \"data\" ? data.data : data.url;\n  }\n  return data;\n}\nfunction convertFromReasoningOutputs(parts) {\n  return parts.map((part) => {\n    if (part.type === \"reasoning\") {\n      return {\n        type: \"reasoning\",\n        text: part.text,\n        ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n      };\n    }\n    return {\n      type: \"reasoning-file\",\n      data: part.file.base64,\n      mediaType: part.file.mediaType,\n      ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n    };\n  });\n}\nfunction convertToReasoningOutputs(parts) {\n  return parts.map((part) => {\n    if (part.type === \"reasoning\") {\n      return {\n        type: \"reasoning\",\n        text: part.text,\n        ...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {}\n      };\n    }\n    const rawData = unwrapReasoningFileData(part.data);\n    const fileData = rawData instanceof ArrayBuffer ? new Uint8Array(rawData) : rawData instanceof URL ? rawData.toString() : rawData;\n    return {\n      type: \"reasoning-file\",\n      file: new DefaultGeneratedFile({\n        data: fileData,\n        mediaType: part.mediaType\n      }),\n      ...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {}\n    };\n  });\n}\n\n// src/generate-text/resolve-tool-approval.ts\nasync function resolveToolApproval({\n  tools,\n  toolCall,\n  toolApproval,\n  messages,\n  toolsContext,\n  runtimeContext\n}) {\n  if (toolApproval != null && typeof toolApproval === \"function\") {\n    return normalizeToolApprovalStatus(\n      await toolApproval({\n        toolCall,\n        tools,\n        toolsContext,\n        messages,\n        runtimeContext\n      })\n    );\n  }\n  const toolName = toolCall.toolName;\n  const tool2 = tools == null ? void 0 : tools[toolName];\n  const input = toolCall.input;\n  const userDefinedToolApprovalStatus = toolApproval == null ? void 0 : toolApproval[toolName];\n  if (userDefinedToolApprovalStatus != null) {\n    const approvalStatus = typeof userDefinedToolApprovalStatus === \"function\" ? await userDefinedToolApprovalStatus(input, {\n      toolCallId: toolCall.toolCallId,\n      messages,\n      toolContext: await validateToolContext({\n        toolName,\n        context: toolsContext == null ? void 0 : toolsContext[toolName],\n        contextSchema: tool2 == null ? void 0 : tool2.contextSchema\n      }),\n      runtimeContext\n    }) : userDefinedToolApprovalStatus;\n    return normalizeToolApprovalStatus(approvalStatus);\n  }\n  if ((tool2 == null ? void 0 : tool2.needsApproval) == null) {\n    return { type: \"not-applicable\" };\n  }\n  const needsApproval = typeof tool2.needsApproval === \"function\" ? await tool2.needsApproval(input, {\n    toolCallId: toolCall.toolCallId,\n    messages,\n    context: await validateToolContext({\n      toolName,\n      context: toolsContext == null ? void 0 : toolsContext[toolName],\n      contextSchema: tool2 == null ? void 0 : tool2.contextSchema\n    })\n  }) : tool2.needsApproval;\n  return needsApproval ? { type: \"user-approval\" } : { type: \"not-applicable\" };\n}\nfunction normalizeToolApprovalStatus(status) {\n  return status === void 0 ? { type: \"not-applicable\" } : typeof status === \"string\" ? { type: status } : status;\n}\n\n// src/telemetry/create-telemetry-dispatcher.ts\nimport { asArray as asArray4 } from \"@ai-sdk/provider-utils\";\n\n// src/util/merge-callbacks.ts\nfunction mergeCallbacks(...callbacks) {\n  return async (event) => {\n    await Promise.allSettled(\n      callbacks.map(async (callback) => {\n        await (callback == null ? void 0 : callback(event));\n      })\n    );\n  };\n}\n\n// src/telemetry/tracing-channel.ts\nvar AI_SDK_TELEMETRY_TRACING_CHANNEL = \"ai:telemetry\";\n\n// src/util/is-node-runtime.ts\nfunction isNodeRuntime() {\n  var _a22;\n  return typeof process !== \"undefined\" && ((_a22 = process.release) == null ? void 0 : _a22.name) === \"node\";\n}\n\n// src/telemetry/tracing-channel-publisher.ts\nvar diagnosticsChannelPromise;\nasync function loadDiagnosticsChannel() {\n  if (!isNodeRuntime()) {\n    return void 0;\n  }\n  if (diagnosticsChannelPromise == null) {\n    diagnosticsChannelPromise = import(\n      /* webpackIgnore: true */\n      \"diagnostics_channel\"\n    ).catch(() => void 0);\n  }\n  return diagnosticsChannelPromise;\n}\nfunction loadBuiltinModule(id) {\n  var _a22;\n  const processWithBuiltins = globalThis.process;\n  try {\n    return (_a22 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a22.call(processWithBuiltins, id);\n  } catch (e) {\n    return void 0;\n  }\n}\nasync function runWithTracingChannelSpan(message, execute) {\n  var _a22;\n  const diagnosticsChannel = await loadDiagnosticsChannel();\n  const tracingChannel = (_a22 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a22.call(\n    diagnosticsChannel,\n    AI_SDK_TELEMETRY_TRACING_CHANNEL\n  );\n  if (tracingChannel == null || tracingChannel.hasSubscribers === false) {\n    return await execute();\n  }\n  let executePromise;\n  let executionResult;\n  let executionError;\n  let hasExecutionResult = false;\n  let hasExecutionError = false;\n  const tracedExecute = () => {\n    try {\n      executePromise = Promise.resolve(execute());\n    } catch (error) {\n      executePromise = Promise.reject(error);\n    }\n    executePromise = executePromise.then(\n      (result) => {\n        executionResult = result;\n        hasExecutionResult = true;\n        return result;\n      },\n      (error) => {\n        executionError = error;\n        hasExecutionError = true;\n        throw error;\n      }\n    );\n    return executePromise;\n  };\n  try {\n    return await tracingChannel.tracePromise(tracedExecute, message);\n  } catch (e) {\n    if (hasExecutionError) {\n      throw executionError;\n    }\n    if (hasExecutionResult) {\n      return executionResult;\n    }\n    if (executePromise != null) {\n      return await executePromise;\n    }\n    return await execute();\n  }\n}\nfunction openTelemetryChannelSpanContext({\n  message,\n  completion\n}) {\n  var _a22;\n  if (!isNodeRuntime()) {\n    return void 0;\n  }\n  const diagnosticsChannel = loadBuiltinModule(\n    \"node:diagnostics_channel\"\n  );\n  const asyncHooks = loadBuiltinModule(\"node:async_hooks\");\n  const tracingChannel = (_a22 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a22.call(\n    diagnosticsChannel,\n    AI_SDK_TELEMETRY_TRACING_CHANNEL\n  );\n  if (tracingChannel == null || tracingChannel.hasSubscribers === false || asyncHooks == null) {\n    Promise.resolve(completion).catch(() => {\n    });\n    return void 0;\n  }\n  const context = message;\n  let asyncResource;\n  let asyncEndPublished = false;\n  const safePublish = (publish) => {\n    try {\n      publish();\n    } catch (e) {\n    }\n  };\n  const publishAsyncEnd = ({\n    result,\n    error\n  }) => {\n    if (asyncEndPublished) {\n      return;\n    }\n    asyncEndPublished = true;\n    if (error !== void 0) {\n      context.error = error;\n      safePublish(() => tracingChannel.error.publish(context));\n    }\n    if (result !== void 0) {\n      context.result = result;\n    }\n    safePublish(() => tracingChannel.asyncEnd.publish(context));\n  };\n  safePublish(() => {\n    tracingChannel.start.runStores(context, () => {\n      asyncResource = new asyncHooks.AsyncResource(\"ai.telemetry\");\n    });\n  });\n  safePublish(() => tracingChannel.end.publish(context));\n  void Promise.resolve(completion).then(\n    (result) => publishAsyncEnd({ result }),\n    (error) => publishAsyncEnd({ error })\n  );\n  return {\n    run: (execute) => asyncResource == null ? execute() : asyncResource.runInAsyncScope(execute)\n  };\n}\n\n// src/telemetry/telemetry-registry.ts\nfunction registerTelemetry(...integrations) {\n  if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {\n    globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n  }\n  globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);\n}\nfunction getGlobalTelemetryIntegrations() {\n  var _a22;\n  return (_a22 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a22 : [];\n}\n\n// src/telemetry/create-telemetry-dispatcher.ts\nfunction augmentEvent(event, telemetry) {\n  return Object.assign(\n    Object.create(Object.getPrototypeOf(event)),\n    event,\n    telemetry\n  );\n}\nfunction createTelemetryDispatcher({\n  telemetry\n}) {\n  if ((telemetry == null ? void 0 : telemetry.isEnabled) === false) {\n    return {};\n  }\n  const localIntegrations = telemetry == null ? void 0 : telemetry.integrations;\n  const integrations = localIntegrations != null ? asArray4(localIntegrations) : getGlobalTelemetryIntegrations();\n  const telemetryMetadata = {\n    recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,\n    recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,\n    functionId: telemetry == null ? void 0 : telemetry.functionId\n  };\n  const mergeTelemetryCallback = (key) => {\n    const integrationCallbacks = integrations.map((integration) => {\n      var _a22;\n      return (_a22 = integration[key]) == null ? void 0 : _a22.bind(integration);\n    }).filter(Boolean).map(\n      (callback) => (event) => callback(augmentEvent(event, telemetryMetadata))\n    );\n    const mergedIntegrationCallback = mergeCallbacks(...integrationCallbacks);\n    return async (event) => {\n      await mergedIntegrationCallback(event);\n    };\n  };\n  const executeLanguageModelCallWrappers = integrations.map((integration) => {\n    var _a22;\n    return (_a22 = integration.executeLanguageModelCall) == null ? void 0 : _a22.bind(integration);\n  }).filter(Boolean);\n  const executeToolWrappers = integrations.map((integration) => {\n    var _a22;\n    return (_a22 = integration.executeTool) == null ? void 0 : _a22.bind(integration);\n  }).filter(Boolean);\n  return {\n    runInTracingChannelSpan: async ({ type, event, execute }) => await runWithTracingChannelSpan(\n      {\n        type,\n        event: augmentEvent(event, telemetryMetadata)\n      },\n      execute\n    ),\n    startTracingChannelContext: ({ type, event, completion }) => openTelemetryChannelSpanContext({\n      message: {\n        type,\n        event: augmentEvent(event, telemetryMetadata)\n      },\n      completion\n    }),\n    onStart: mergeTelemetryCallback(\"onStart\"),\n    onStepStart: mergeTelemetryCallback(\"onStepStart\"),\n    onLanguageModelCallStart: mergeTelemetryCallback(\n      \"onLanguageModelCallStart\"\n    ),\n    onLanguageModelCallEnd: mergeTelemetryCallback(\"onLanguageModelCallEnd\"),\n    onToolExecutionStart: mergeTelemetryCallback(\"onToolExecutionStart\"),\n    onToolExecutionEnd: mergeTelemetryCallback(\"onToolExecutionEnd\"),\n    // Fan out step-end events to both the new `onStepEnd` callback and the\n    // deprecated `onStepFinish` callback so integrations that still implement\n    // only `onStepFinish` keep receiving step-end events during the deprecation\n    // window.\n    onStepEnd: mergeCallbacks(\n      mergeTelemetryCallback(\"onStepEnd\"),\n      mergeTelemetryCallback(\"onStepFinish\")\n    ),\n    onObjectStepStart: mergeTelemetryCallback(\"onObjectStepStart\"),\n    onObjectStepEnd: mergeTelemetryCallback(\"onObjectStepEnd\"),\n    onEmbedStart: mergeTelemetryCallback(\"onEmbedStart\"),\n    onEmbedEnd: mergeTelemetryCallback(\"onEmbedEnd\"),\n    onRerankStart: mergeTelemetryCallback(\"onRerankStart\"),\n    onRerankEnd: mergeTelemetryCallback(\"onRerankEnd\"),\n    onEnd: mergeTelemetryCallback(\"onEnd\"),\n    onAbort: mergeTelemetryCallback(\"onAbort\"),\n    onError: mergeTelemetryCallback(\"onError\"),\n    /**\n     * Runs provider calls inside integration-specific context so\n     * auto-instrumented provider requests can be associated with model work.\n     */\n    executeLanguageModelCall: async ({ execute, ...event }) => {\n      const augmentedEvent = augmentEvent(event, telemetryMetadata);\n      let wrappedExecute = execute;\n      for (const executeWrapper of executeLanguageModelCallWrappers) {\n        const innerExecute = wrappedExecute;\n        wrappedExecute = () => executeWrapper({ ...augmentedEvent, execute: innerExecute });\n      }\n      return await runWithTracingChannelSpan(\n        { type: \"languageModelCall\", event: augmentedEvent },\n        wrappedExecute\n      );\n    },\n    /**\n     * Composes all `executeTool` wrappers around the original tool execution.\n     * Each wrapper receives an `execute` function that calls the next wrapper in\n     * the chain, so integrations can establish nested telemetry context before\n     * delegating to the underlying tool.\n     */\n    executeTool: async ({ execute, ...event }) => {\n      const augmentedEvent = augmentEvent(event, telemetryMetadata);\n      let wrappedExecute = execute;\n      for (const executeWrapper of executeToolWrappers) {\n        const innerExecute = wrappedExecute;\n        wrappedExecute = () => executeWrapper({ ...augmentedEvent, execute: innerExecute });\n      }\n      return await wrappedExecute();\n    }\n  };\n}\n\n// src/generate-text/reasoning.ts\nfunction asReasoningText(reasoningParts) {\n  const reasoningText = reasoningParts.map((part) => \"text\" in part ? part.text : \"\").join(\"\");\n  return reasoningText.length > 0 ? reasoningText : void 0;\n}\n\n// src/generate-text/step-result.ts\nvar DefaultStepResult = class {\n  constructor({\n    callId,\n    stepNumber,\n    provider,\n    modelId,\n    runtimeContext,\n    toolsContext,\n    content,\n    finishReason,\n    rawFinishReason,\n    usage,\n    performance,\n    warnings,\n    request,\n    response,\n    providerMetadata\n  }) {\n    this.callId = callId;\n    this.stepNumber = stepNumber;\n    this.model = { provider, modelId };\n    this.runtimeContext = runtimeContext;\n    this.toolsContext = toolsContext;\n    this.content = content;\n    this.finishReason = finishReason;\n    this.rawFinishReason = rawFinishReason;\n    this.usage = usage;\n    this.performance = performance;\n    this.warnings = warnings;\n    this.request = request;\n    this.response = response;\n    this.providerMetadata = providerMetadata;\n  }\n  get text() {\n    return this.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\");\n  }\n  get reasoning() {\n    return convertFromReasoningOutputs(\n      this.content.filter(\n        (part) => part.type === \"reasoning\" || part.type === \"reasoning-file\"\n      )\n    );\n  }\n  get reasoningText() {\n    return asReasoningText(this.reasoning);\n  }\n  get files() {\n    return this.content.filter((part) => part.type === \"file\").map((part) => part.file);\n  }\n  get sources() {\n    return this.content.filter((part) => part.type === \"source\");\n  }\n  get toolCalls() {\n    return this.content.filter((part) => part.type === \"tool-call\");\n  }\n  get staticToolCalls() {\n    return this.toolCalls.filter(\n      (toolCall) => toolCall.dynamic !== true\n    );\n  }\n  get dynamicToolCalls() {\n    return this.toolCalls.filter(\n      (toolCall) => toolCall.dynamic === true\n    );\n  }\n  get toolResults() {\n    return this.content.filter((part) => part.type === \"tool-result\");\n  }\n  get staticToolResults() {\n    return this.toolResults.filter(\n      (toolResult) => toolResult.dynamic !== true\n    );\n  }\n  get dynamicToolResults() {\n    return this.toolResults.filter(\n      (toolResult) => toolResult.dynamic === true\n    );\n  }\n};\n\n// src/generate-text/restricted-telemetry-dispatcher.ts\nfunction filterIncludedContext({\n  context,\n  includeContext\n}) {\n  if (context == null) {\n    return {};\n  }\n  return Object.fromEntries(\n    Object.entries(context).filter(\n      ([key]) => (includeContext == null ? void 0 : includeContext[key]) === true\n    )\n  );\n}\nfunction restrictStepResult({\n  step,\n  includeRuntimeContext,\n  includeToolsContext\n}) {\n  return new DefaultStepResult({\n    callId: step.callId,\n    stepNumber: step.stepNumber,\n    provider: step.model.provider,\n    modelId: step.model.modelId,\n    runtimeContext: filterIncludedContext({\n      context: step.runtimeContext,\n      includeContext: includeRuntimeContext\n    }),\n    toolsContext: filterToolsContext({\n      toolsContext: step.toolsContext,\n      includeToolsContext\n    }),\n    content: step.content,\n    finishReason: step.finishReason,\n    rawFinishReason: step.rawFinishReason,\n    usage: step.usage,\n    performance: step.performance,\n    warnings: step.warnings,\n    request: step.request,\n    response: step.response,\n    providerMetadata: step.providerMetadata\n  });\n}\nfunction filterToolsContext({\n  toolsContext,\n  includeToolsContext\n}) {\n  if (includeToolsContext == null) {\n    return {};\n  }\n  return Object.fromEntries(\n    Object.entries(toolsContext).map(([toolName, toolContext]) => [\n      toolName,\n      filterToolContext({\n        toolName,\n        toolContext,\n        includeToolsContext\n      })\n    ])\n  );\n}\nfunction filterToolContext({\n  toolName,\n  toolContext,\n  includeToolsContext\n}) {\n  const includeToolContext = includeToolsContext == null ? void 0 : includeToolsContext[toolName];\n  return filterIncludedContext({\n    context: toolContext,\n    includeContext: includeToolContext\n  });\n}\nfunction createRestrictedTelemetryDispatcher({\n  telemetry,\n  includeRuntimeContext,\n  includeToolsContext\n}) {\n  const telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n  return {\n    ...telemetryDispatcher,\n    onStart: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onStart) == null ? void 0 : _a22.call(telemetryDispatcher, {\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: includeRuntimeContext\n        }),\n        toolsContext: filterToolsContext({\n          toolsContext: event.toolsContext,\n          includeToolsContext\n        })\n      });\n    },\n    onStepStart: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onStepStart) == null ? void 0 : _a22.call(telemetryDispatcher, {\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: includeRuntimeContext\n        }),\n        steps: event.steps.map(\n          (step) => restrictStepResult({\n            step,\n            includeRuntimeContext,\n            includeToolsContext\n          })\n        ),\n        toolsContext: filterToolsContext({\n          toolsContext: event.toolsContext,\n          includeToolsContext\n        })\n      });\n    },\n    onStepEnd: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a22.call(\n        telemetryDispatcher,\n        restrictStepResult({\n          step: event,\n          includeRuntimeContext,\n          includeToolsContext\n        })\n      );\n    },\n    onStepFinish: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a22.call(\n        telemetryDispatcher,\n        restrictStepResult({\n          step: event,\n          includeRuntimeContext,\n          includeToolsContext\n        })\n      );\n    },\n    onEnd: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onEnd) == null ? void 0 : _a22.call(\n        telemetryDispatcher,\n        ((restrictedSteps) => {\n          return {\n            ...event,\n            runtimeContext: filterIncludedContext({\n              context: event.runtimeContext,\n              includeContext: includeRuntimeContext\n            }),\n            steps: restrictedSteps,\n            finalStep: restrictedSteps.at(-1),\n            toolsContext: filterToolsContext({\n              toolsContext: event.toolsContext,\n              includeToolsContext\n            })\n          };\n        })(\n          event.steps.map(\n            (step) => restrictStepResult({\n              step,\n              includeRuntimeContext,\n              includeToolsContext\n            })\n          )\n        )\n      );\n    },\n    onAbort: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onAbort) == null ? void 0 : _a22.call(telemetryDispatcher, {\n        ...event,\n        steps: event.steps.map(\n          (step) => restrictStepResult({\n            step,\n            includeRuntimeContext,\n            includeToolsContext\n          })\n        )\n      });\n    },\n    onToolExecutionStart: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _a22.call(telemetryDispatcher, {\n        ...event,\n        toolContext: filterToolContext({\n          toolName: event.toolCall.toolName,\n          toolContext: event.toolContext,\n          includeToolsContext\n        })\n      });\n    },\n    onToolExecutionEnd: (event) => {\n      var _a22;\n      return (_a22 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _a22.call(telemetryDispatcher, {\n        ...event,\n        toolContext: filterToolContext({\n          toolName: event.toolCall.toolName,\n          toolContext: event.toolContext,\n          includeToolsContext\n        })\n      });\n    }\n  };\n}\n\n// src/generate-text/stop-condition.ts\nfunction isStepCount(stepCount) {\n  return ({ steps }) => steps.length === stepCount;\n}\nfunction isLoopFinished() {\n  return () => false;\n}\nfunction hasToolCall(...toolName) {\n  return ({ steps }) => {\n    var _a22, _b, _c;\n    return (_c = (_b = (_a22 = steps[steps.length - 1]) == null ? void 0 : _a22.toolCalls) == null ? void 0 : _b.some(\n      (toolCall) => toolName.includes(toolCall.toolName)\n    )) != null ? _c : false;\n  };\n}\nasync function isStopConditionMet({\n  stopConditions,\n  steps\n}) {\n  return (await Promise.all(stopConditions.map((condition) => condition({ steps })))).some((result) => result);\n}\n\n// src/generate-text/sum-token-counts.ts\nfunction sumTokenCounts(tokenCount1, tokenCount2) {\n  return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);\n}\n\n// src/generate-text/to-response-messages.ts\nasync function toResponseMessages({\n  content: inputContent,\n  tools\n}) {\n  const responseMessages = [];\n  const content = [];\n  for (const part of inputContent) {\n    if (part.type === \"source\") {\n      continue;\n    }\n    if ((part.type === \"tool-result\" || part.type === \"tool-error\") && !part.providerExecuted) {\n      continue;\n    }\n    if (part.type === \"text\" && part.text.length === 0) {\n      continue;\n    }\n    switch (part.type) {\n      case \"text\":\n        content.push({\n          type: \"text\",\n          text: part.text,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      case \"custom\":\n        content.push({\n          type: \"custom\",\n          kind: part.kind,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      case \"reasoning\":\n        content.push({\n          type: \"reasoning\",\n          text: part.text,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      case \"file\":\n        content.push({\n          type: \"file\",\n          data: part.file.base64,\n          mediaType: part.file.mediaType,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      case \"reasoning-file\":\n        content.push({\n          type: \"reasoning-file\",\n          data: part.file.base64,\n          mediaType: part.file.mediaType,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      case \"tool-call\":\n        content.push({\n          type: \"tool-call\",\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          input: part.invalid && typeof part.input !== \"object\" ? {} : part.input,\n          providerExecuted: part.providerExecuted,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      case \"tool-result\": {\n        const output = await createToolModelOutput({\n          toolCallId: part.toolCallId,\n          input: part.input,\n          tool: tools == null ? void 0 : tools[part.toolName],\n          output: part.output,\n          errorMode: \"none\"\n        });\n        content.push({\n          type: \"tool-result\",\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          output,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      }\n      case \"tool-error\": {\n        const output = await createToolModelOutput({\n          toolCallId: part.toolCallId,\n          input: part.input,\n          tool: tools == null ? void 0 : tools[part.toolName],\n          output: part.error,\n          errorMode: \"json\"\n        });\n        content.push({\n          type: \"tool-result\",\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          output,\n          providerOptions: part.providerMetadata\n        });\n        break;\n      }\n      case \"tool-approval-request\":\n        content.push({\n          type: \"tool-approval-request\",\n          approvalId: part.approvalId,\n          toolCallId: part.toolCall.toolCallId,\n          isAutomatic: part.isAutomatic,\n          ...part.signature != null ? { signature: part.signature } : {}\n        });\n        break;\n    }\n  }\n  if (content.length > 0) {\n    responseMessages.push({\n      role: \"assistant\",\n      content\n    });\n  }\n  const toolResultContent = [];\n  for (const part of inputContent) {\n    if (part.type !== \"tool-approval-response\" && part.type !== \"tool-result\" && part.type !== \"tool-error\") {\n      continue;\n    }\n    if (part.type === \"tool-approval-response\") {\n      toolResultContent.push({\n        type: \"tool-approval-response\",\n        approvalId: part.approvalId,\n        approved: part.approved,\n        reason: part.reason,\n        providerExecuted: part.providerExecuted\n      });\n      if (part.approved === false) {\n        toolResultContent.push({\n          type: \"tool-result\",\n          toolCallId: part.toolCall.toolCallId,\n          toolName: part.toolCall.toolName,\n          output: {\n            type: \"execution-denied\",\n            reason: part.reason\n          }\n        });\n      }\n      continue;\n    }\n    if (part.providerExecuted) {\n      continue;\n    }\n    const output = await createToolModelOutput({\n      toolCallId: part.toolCallId,\n      input: part.input,\n      tool: tools == null ? void 0 : tools[part.toolName],\n      output: part.type === \"tool-result\" ? part.output : part.error,\n      errorMode: part.type === \"tool-error\" ? \"text\" : \"none\"\n    });\n    toolResultContent.push({\n      type: \"tool-result\",\n      toolCallId: part.toolCallId,\n      toolName: part.toolName,\n      output,\n      ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n    });\n  }\n  if (toolResultContent.length > 0) {\n    responseMessages.push({\n      role: \"tool\",\n      content: toolResultContent\n    });\n  }\n  return responseMessages;\n}\n\n// src/generate-text/tool-approval-signature.ts\nimport {\n  convertBase64ToUint8Array as convertBase64ToUint8Array2,\n  convertUint8ArrayToBase64 as convertUint8ArrayToBase642\n} from \"@ai-sdk/provider-utils\";\nvar encoder = new TextEncoder();\nfunction canonicalJSON(value) {\n  if (value === null || value === void 0) {\n    return JSON.stringify(value);\n  }\n  if (typeof value !== \"object\") {\n    return JSON.stringify(value);\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map(canonicalJSON).join(\",\")}]`;\n  }\n  const keys = Object.keys(value).sort();\n  const entries = keys.map(\n    (k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}`\n  );\n  return `{${entries.join(\",\")}}`;\n}\nfunction toBase64url(bytes) {\n  return convertUint8ArrayToBase642(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/g, \"\");\n}\nfunction fromBase64url(str) {\n  return convertBase64ToUint8Array2(str);\n}\nasync function importKey(secret) {\n  const keyData = typeof secret === \"string\" ? encoder.encode(secret) : secret;\n  return crypto.subtle.importKey(\n    \"raw\",\n    keyData,\n    { name: \"HMAC\", hash: \"SHA-256\" },\n    false,\n    [\"sign\", \"verify\"]\n  );\n}\nasync function hashInput(input) {\n  const canonical = canonicalJSON(input);\n  const digest = await crypto.subtle.digest(\n    \"SHA-256\",\n    encoder.encode(canonical)\n  );\n  return toBase64url(new Uint8Array(digest));\n}\nfunction buildPayload(approvalId, toolCallId, toolName, inputDigest) {\n  return encoder.encode(\n    `${approvalId}\n${toolCallId}\n${toolName}\n${inputDigest}`\n  );\n}\nasync function signToolApproval({\n  secret,\n  approvalId,\n  toolCallId,\n  toolName,\n  input\n}) {\n  const key = await importKey(secret);\n  const inputDigest = await hashInput(input);\n  const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n  const sig = await crypto.subtle.sign(\"HMAC\", key, payload);\n  return toBase64url(new Uint8Array(sig));\n}\nasync function verifyToolApprovalSignature({\n  secret,\n  signature,\n  approvalId,\n  toolCallId,\n  toolName,\n  input\n}) {\n  const key = await importKey(secret);\n  const inputDigest = await hashInput(input);\n  const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n  const sigBytes = fromBase64url(signature);\n  return crypto.subtle.verify(\"HMAC\", key, sigBytes, payload);\n}\nasync function maybeSignApproval({\n  secret,\n  approvalId,\n  toolCallId,\n  toolName,\n  input\n}) {\n  if (secret == null)\n    return void 0;\n  return signToolApproval({ secret, approvalId, toolCallId, toolName, input });\n}\n\n// src/generate-text/validate-tool-approvals.ts\nimport {\n  asSchema as asSchema4,\n  isExecutableTool as isExecutableTool2,\n  safeValidateTypes as safeValidateTypes4\n} from \"@ai-sdk/provider-utils\";\nasync function validateApprovedToolApprovals({\n  approvedToolApprovals,\n  tools,\n  toolApproval,\n  messages,\n  toolsContext,\n  runtimeContext,\n  toolApprovalSecret\n}) {\n  var _a22;\n  const approved = [];\n  const denied = [];\n  for (const approval of approvedToolApprovals) {\n    const { toolCall, approvalRequest } = approval;\n    const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n    if (toolApprovalSecret != null) {\n      if (approvalRequest.signature == null) {\n        throw new InvalidToolApprovalSignatureError({\n          approvalId: approvalRequest.approvalId,\n          toolCallId: toolCall.toolCallId,\n          reason: \"missing signature\"\n        });\n      }\n      const valid = await verifyToolApprovalSignature({\n        secret: toolApprovalSecret,\n        signature: approvalRequest.signature,\n        approvalId: approvalRequest.approvalId,\n        toolCallId: toolCall.toolCallId,\n        toolName: toolCall.toolName,\n        input: toolCall.input\n      });\n      if (!valid) {\n        throw new InvalidToolApprovalSignatureError({\n          approvalId: approvalRequest.approvalId,\n          toolCallId: toolCall.toolCallId,\n          reason: \"invalid signature\"\n        });\n      }\n    }\n    if (isExecutableTool2(tool2) && tool2.inputSchema != null) {\n      const validation = await safeValidateTypes4({\n        value: toolCall.input,\n        schema: asSchema4(tool2.inputSchema)\n      });\n      if (!validation.success) {\n        throw new InvalidToolInputError({\n          toolName: toolCall.toolName,\n          toolInput: JSON.stringify(toolCall.input),\n          cause: validation.error\n        });\n      }\n    }\n    const approvalStatus = await resolveToolApproval({\n      tools,\n      toolApproval,\n      toolCall,\n      messages,\n      toolsContext,\n      runtimeContext\n    });\n    if (approvalStatus.type === \"denied\") {\n      denied.push({\n        ...approval,\n        approvalResponse: {\n          ...approval.approvalResponse,\n          approved: false,\n          reason: (_a22 = approvalStatus.reason) != null ? _a22 : approval.approvalResponse.reason\n        }\n      });\n    } else {\n      approved.push(approval);\n    }\n  }\n  return { approvedToolApprovals: approved, deniedToolApprovals: denied };\n}\n\n// src/generate-text/generate-text.ts\nvar originalGenerateId = createIdGenerator({\n  prefix: \"aitxt\",\n  size: 24\n});\nvar originalGenerateCallId = createIdGenerator({\n  prefix: \"call\",\n  size: 24\n});\nasync function generateText({\n  model: modelArg,\n  tools,\n  toolChoice,\n  instructions,\n  system,\n  prompt,\n  messages,\n  allowSystemInMessages,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  timeout,\n  headers,\n  stopWhen = isStepCount(1),\n  experimental_sandbox: sandbox,\n  output,\n  toolApproval,\n  experimental_toolApprovalSecret,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  providerOptions,\n  activeTools,\n  toolOrder,\n  prepareStep,\n  experimental_repairToolCall: repairToolCall,\n  experimental_refineToolInput: refineToolInput,\n  experimental_download: download2,\n  runtimeContext = {},\n  toolsContext = {},\n  experimental_include,\n  include = experimental_include,\n  _internal: {\n    generateId: generateId2 = originalGenerateId,\n    generateCallId = originalGenerateCallId,\n    now: now2 = now\n  } = {},\n  onStart,\n  experimental_onStart,\n  onStepStart,\n  experimental_onStepStart,\n  onLanguageModelCallStart,\n  experimental_onLanguageModelCallStart,\n  onLanguageModelCallEnd,\n  experimental_onLanguageModelCallEnd,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  experimental_onToolCallStart,\n  experimental_onToolCallFinish,\n  onStepEnd,\n  onStepFinish,\n  onFinish,\n  onEnd = onFinish,\n  ...settings\n}) {\n  var _a22, _b, _c, _d;\n  include = {\n    requestBody: (_a22 = include == null ? void 0 : include.requestBody) != null ? _a22 : false,\n    requestMessages: (_b = include == null ? void 0 : include.requestMessages) != null ? _b : false,\n    responseBody: (_c = include == null ? void 0 : include.responseBody) != null ? _c : false\n  };\n  const model = resolveLanguageModel(modelArg);\n  const stopConditions = asArray5(stopWhen);\n  const resolvedOnStart = onStart != null ? onStart : experimental_onStart;\n  const resolvedOnStepStart = onStepStart != null ? onStepStart : experimental_onStepStart;\n  const resolvedOnLanguageModelCallStart = onLanguageModelCallStart != null ? onLanguageModelCallStart : experimental_onLanguageModelCallStart;\n  const resolvedOnLanguageModelCallEnd = onLanguageModelCallEnd != null ? onLanguageModelCallEnd : experimental_onLanguageModelCallEnd;\n  const resolvedOnToolExecutionStart = onToolExecutionStart != null ? onToolExecutionStart : experimental_onToolCallStart;\n  const resolvedOnToolExecutionEnd = onToolExecutionEnd != null ? onToolExecutionEnd : experimental_onToolCallFinish;\n  const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish;\n  const totalTimeoutMs = getTotalTimeoutMs(timeout);\n  const stepTimeoutMs = getStepTimeoutMs(timeout);\n  const stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n  const mergedAbortSignal = mergeAbortSignals(\n    abortSignal,\n    totalTimeoutMs,\n    stepAbortController == null ? void 0 : stepAbortController.signal\n  );\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal: mergedAbortSignal\n  });\n  const callSettings = prepareLanguageModelCallOptions(settings);\n  const headersWithUserAgent = withUserAgentSuffix2(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const initialPrompt = await standardizePrompt({\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages\n  });\n  const callId = generateCallId();\n  const telemetryDispatcher = createRestrictedTelemetryDispatcher({\n    telemetry,\n    includeRuntimeContext: telemetry == null ? void 0 : telemetry.includeRuntimeContext,\n    includeToolsContext: telemetry == null ? void 0 : telemetry.includeToolsContext\n  });\n  const runInTracingChannelSpan = (_d = telemetryDispatcher.runInTracingChannelSpan) != null ? _d : async ({ execute }) => await execute();\n  const generateTextStartEvent = {\n    callId,\n    operationId: \"ai.generateText\",\n    provider: model.provider,\n    modelId: model.modelId,\n    instructions: initialPrompt.instructions,\n    messages: initialPrompt.messages,\n    tools,\n    toolChoice,\n    activeTools,\n    toolOrder,\n    maxOutputTokens: callSettings.maxOutputTokens,\n    temperature: callSettings.temperature,\n    topP: callSettings.topP,\n    topK: callSettings.topK,\n    presencePenalty: callSettings.presencePenalty,\n    frequencyPenalty: callSettings.frequencyPenalty,\n    stopSequences: callSettings.stopSequences,\n    seed: callSettings.seed,\n    reasoning: callSettings.reasoning,\n    maxRetries,\n    timeout,\n    headers: headersWithUserAgent,\n    providerOptions,\n    output,\n    runtimeContext,\n    toolsContext\n  };\n  const executeGenerateText = async () => {\n    var _a23;\n    await notify({\n      event: generateTextStartEvent,\n      callbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n    });\n    try {\n      const initialMessages = initialPrompt.messages;\n      const initialResponseMessages = [];\n      const {\n        approvedToolApprovals,\n        deniedToolApprovals: collectedDeniedToolApprovals\n      } = collectToolApprovals({ messages: initialMessages });\n      const {\n        approvedToolApprovals: localApprovedToolApprovals,\n        deniedToolApprovals: revalidationDeniedToolApprovals\n      } = await validateApprovedToolApprovals({\n        approvedToolApprovals: approvedToolApprovals.filter(\n          (toolApproval2) => !toolApproval2.toolCall.providerExecuted\n        ),\n        tools,\n        toolApproval,\n        messages: initialMessages,\n        toolsContext,\n        runtimeContext,\n        toolApprovalSecret: experimental_toolApprovalSecret\n      });\n      const deniedToolApprovals = [\n        ...collectedDeniedToolApprovals,\n        ...revalidationDeniedToolApprovals\n      ];\n      if (deniedToolApprovals.length > 0 || localApprovedToolApprovals.length > 0) {\n        const toolResults2 = await executeTools({\n          toolCalls: localApprovedToolApprovals.map(\n            (toolApproval2) => toolApproval2.toolCall\n          ),\n          tools,\n          callId,\n          messages: initialMessages,\n          abortSignal: mergedAbortSignal,\n          timeout,\n          experimental_sandbox: sandbox,\n          toolsContext,\n          onToolExecutionStart: (event) => notify({\n            event,\n            callbacks: [\n              resolvedOnToolExecutionStart,\n              telemetryDispatcher.onToolExecutionStart\n            ]\n          }),\n          onToolExecutionEnd: (event) => notify({\n            event,\n            callbacks: [\n              resolvedOnToolExecutionEnd,\n              telemetryDispatcher.onToolExecutionEnd\n            ]\n          }),\n          executeToolInTelemetryContext: telemetryDispatcher.executeTool,\n          runInTracingChannelSpan\n        });\n        const toolContent = [];\n        for (const result of toolResults2) {\n          const output2 = result.output;\n          const modelOutput = await createToolModelOutput({\n            toolCallId: output2.toolCallId,\n            input: output2.input,\n            tool: tools == null ? void 0 : tools[output2.toolName],\n            output: output2.type === \"tool-result\" ? output2.output : output2.error,\n            errorMode: output2.type === \"tool-error\" ? \"text\" : \"none\"\n          });\n          toolContent.push({\n            type: \"tool-result\",\n            toolCallId: output2.toolCallId,\n            toolName: output2.toolName,\n            output: modelOutput\n          });\n        }\n        for (const toolApproval2 of deniedToolApprovals) {\n          toolContent.push({\n            type: \"tool-result\",\n            toolCallId: toolApproval2.toolCall.toolCallId,\n            toolName: toolApproval2.toolCall.toolName,\n            output: {\n              type: \"execution-denied\",\n              reason: toolApproval2.approvalResponse.reason,\n              // For provider-executed tools, include approvalId so provider can correlate\n              ...toolApproval2.toolCall.providerExecuted && {\n                providerOptions: {\n                  openai: {\n                    approvalId: toolApproval2.approvalResponse.approvalId\n                  }\n                }\n              }\n            }\n          });\n        }\n        initialResponseMessages.push({\n          role: \"tool\",\n          content: toolContent\n        });\n      }\n      const callSettings2 = prepareLanguageModelCallOptions(settings);\n      let currentModelResponse;\n      let clientToolCalls = [];\n      let clientToolOutputs = [];\n      let toolApprovalResponses = [];\n      let deniedToolApprovalResponses = [];\n      const steps = [];\n      let instructionsForNextStep = initialPrompt.instructions;\n      let messagesForNextStep = [\n        ...initialMessages,\n        ...initialResponseMessages\n      ];\n      const pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n      do {\n        const stepTimeoutId = setAbortTimeout({\n          abortController: stepAbortController,\n          label: \"Step\",\n          timeoutMs: stepTimeoutMs\n        });\n        const stepNumber = steps.length;\n        try {\n          await runInTracingChannelSpan({\n            type: \"step\",\n            event: { callId, stepNumber },\n            execute: async () => {\n              var _a24, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;\n              const accumulatedResponseMessages = [\n                ...initialResponseMessages,\n                ...steps.flatMap((step) => step.response.messages)\n              ];\n              const stepInputMessages = messagesForNextStep;\n              const prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n                model,\n                steps,\n                stepNumber: steps.length,\n                instructions: instructionsForNextStep,\n                initialInstructions: initialPrompt.instructions,\n                messages: stepInputMessages,\n                initialMessages,\n                responseMessages: accumulatedResponseMessages,\n                runtimeContext,\n                toolsContext,\n                experimental_sandbox: sandbox\n              }));\n              const stepSandbox = (_a24 = prepareStepResult == null ? void 0 : prepareStepResult.experimental_sandbox) != null ? _a24 : sandbox;\n              const stepModel = resolveLanguageModel(\n                (_b2 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _b2 : model\n              );\n              const stepInstructions = (_d2 = (_c2 = prepareStepResult == null ? void 0 : prepareStepResult.instructions) != null ? _c2 : prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _d2 : instructionsForNextStep;\n              const promptMessages = await convertToLanguageModelPrompt({\n                prompt: {\n                  instructions: stepInstructions,\n                  messages: (_e = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _e : stepInputMessages\n                },\n                supportedUrls: await stepModel.supportedUrls,\n                download: download2,\n                provider: stepModel.provider.split(\".\")[0]\n              });\n              runtimeContext = (_f = prepareStepResult == null ? void 0 : prepareStepResult.runtimeContext) != null ? _f : runtimeContext;\n              toolsContext = (_g = prepareStepResult == null ? void 0 : prepareStepResult.toolsContext) != null ? _g : toolsContext;\n              const stepActiveTools = filterActiveTools({\n                tools,\n                activeTools: (_h = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _h : activeTools\n              });\n              const stepToolOrder = (_i = prepareStepResult == null ? void 0 : prepareStepResult.toolOrder) != null ? _i : toolOrder;\n              const stepTools = await prepareTools({\n                tools: stepActiveTools,\n                toolOrder: stepToolOrder,\n                // active tools context is a subset of the tools context, so we can cast to the unknown type\n                toolsContext,\n                experimental_sandbox: stepSandbox\n              });\n              const stepToolChoice = prepareToolChoice({\n                toolChoice: (_j = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _j : toolChoice\n              });\n              const stepMessages = (_k = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _k : stepInputMessages;\n              const stepProviderOptions = mergeObjects(\n                providerOptions,\n                prepareStepResult == null ? void 0 : prepareStepResult.providerOptions\n              );\n              await notify({\n                event: {\n                  callId,\n                  provider: stepModel.provider,\n                  modelId: stepModel.modelId,\n                  stepNumber,\n                  instructions: stepInstructions,\n                  messages: stepMessages,\n                  tools,\n                  toolChoice: (_l = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _l : toolChoice,\n                  activeTools: (_m = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _m : activeTools,\n                  toolOrder: stepToolOrder,\n                  steps: [...steps],\n                  providerOptions: stepProviderOptions,\n                  output,\n                  runtimeContext,\n                  promptMessages,\n                  stepTools,\n                  stepToolChoice,\n                  toolsContext\n                },\n                callbacks: [\n                  resolvedOnStepStart,\n                  telemetryDispatcher.onStepStart\n                ]\n              });\n              const languageModelCallContext = {\n                provider: stepModel.provider,\n                modelId: stepModel.modelId,\n                instructions: stepInstructions,\n                messages: stepMessages,\n                tools: stepTools,\n                ...callSettings2\n              };\n              const languageModelCallStartEvent = {\n                callId,\n                ...languageModelCallContext\n              };\n              const stepStartTimestampMs = now2();\n              await notify({\n                event: languageModelCallStartEvent,\n                callbacks: [\n                  resolvedOnLanguageModelCallStart,\n                  telemetryDispatcher.onLanguageModelCallStart\n                ]\n              });\n              const executeLanguageModelCallInTelemetryContext = (_n = telemetryDispatcher.executeLanguageModelCall) != null ? _n : async ({ execute }) => await execute();\n              currentModelResponse = await retry(async () => {\n                var _a25, _b3, _c3, _d3, _e2, _f2, _g2, _h2;\n                const result = await executeLanguageModelCallInTelemetryContext(\n                  {\n                    ...languageModelCallStartEvent,\n                    execute: async () => await stepModel.doGenerate({\n                      ...callSettings2,\n                      tools: stepTools,\n                      toolChoice: stepToolChoice,\n                      responseFormat: await (output == null ? void 0 : output.responseFormat),\n                      prompt: promptMessages,\n                      providerOptions: stepProviderOptions,\n                      abortSignal: mergedAbortSignal,\n                      headers: headersWithUserAgent\n                    })\n                  }\n                );\n                const responseData = {\n                  id: (_b3 = (_a25 = result.response) == null ? void 0 : _a25.id) != null ? _b3 : generateId2(),\n                  timestamp: (_d3 = (_c3 = result.response) == null ? void 0 : _c3.timestamp) != null ? _d3 : /* @__PURE__ */ new Date(),\n                  modelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,\n                  headers: (_g2 = result.response) == null ? void 0 : _g2.headers,\n                  body: (_h2 = result.response) == null ? void 0 : _h2.body\n                };\n                return { ...result, response: responseData };\n              });\n              const responseTimeMs = now2() - stepStartTimestampMs;\n              const stepUsage = asLanguageModelUsage(\n                currentModelResponse.usage\n              );\n              const stepToolCalls = await Promise.all(\n                currentModelResponse.content.filter(\n                  (part) => part.type === \"tool-call\"\n                ).map(\n                  (toolCall) => parseToolCall({\n                    toolCall,\n                    tools,\n                    repairToolCall,\n                    refineToolInput,\n                    instructions: stepInstructions,\n                    messages: stepMessages\n                  })\n                )\n              );\n              const toolApprovalRequests = {};\n              const stepToolApprovalResponses = {};\n              const blockedToolCallIds = /* @__PURE__ */ new Set();\n              const modelCallContent = asContent({\n                content: currentModelResponse.content,\n                toolCalls: stepToolCalls,\n                toolOutputs: [],\n                toolApprovalRequests: [],\n                toolApprovalResponses: [],\n                tools\n              });\n              await notify({\n                event: {\n                  callId,\n                  provider: stepModel.provider,\n                  modelId: stepModel.modelId,\n                  finishReason: currentModelResponse.finishReason.unified,\n                  usage: stepUsage,\n                  content: modelCallContent,\n                  responseId: currentModelResponse.response.id,\n                  performance: {\n                    responseTimeMs,\n                    effectiveOutputTokensPerSecond: calculateTokensPerSecond({\n                      tokens: stepUsage.outputTokens,\n                      durationMs: responseTimeMs\n                    }),\n                    outputTokensPerSecond: void 0,\n                    inputTokensPerSecond: void 0,\n                    effectiveTotalTokensPerSecond: calculateTokensPerSecond({\n                      tokens: sumTokenCounts(\n                        stepUsage.inputTokens,\n                        stepUsage.outputTokens\n                      ),\n                      durationMs: responseTimeMs\n                    }),\n                    timeToFirstOutputMs: void 0\n                  }\n                },\n                callbacks: [\n                  resolvedOnLanguageModelCallEnd,\n                  telemetryDispatcher.onLanguageModelCallEnd\n                ]\n              });\n              for (const toolCall of stepToolCalls) {\n                if (toolCall.invalid) {\n                  continue;\n                }\n                const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n                if (tool2 == null) {\n                  continue;\n                }\n                if ((tool2 == null ? void 0 : tool2.onInputAvailable) != null) {\n                  await tool2.onInputAvailable({\n                    input: toolCall.input,\n                    toolCallId: toolCall.toolCallId,\n                    messages: stepMessages,\n                    abortSignal: mergedAbortSignal,\n                    context: runtimeContext\n                  });\n                }\n                const toolApprovalStatus = await resolveToolApproval({\n                  tools,\n                  toolApproval,\n                  toolCall,\n                  messages: stepMessages,\n                  toolsContext,\n                  runtimeContext\n                });\n                if (toolApprovalStatus.type === \"not-applicable\") {\n                  continue;\n                }\n                const approvalId = generateId2();\n                const signature = await maybeSignApproval({\n                  secret: experimental_toolApprovalSecret,\n                  approvalId,\n                  toolCallId: toolCall.toolCallId,\n                  toolName: toolCall.toolName,\n                  input: toolCall.input\n                });\n                switch (toolApprovalStatus.type) {\n                  case \"user-approval\": {\n                    toolApprovalRequests[toolCall.toolCallId] = {\n                      type: \"tool-approval-request\",\n                      approvalId,\n                      toolCall,\n                      ...signature != null ? { signature } : {}\n                    };\n                    blockedToolCallIds.add(toolCall.toolCallId);\n                    break;\n                  }\n                  case \"approved\": {\n                    toolApprovalRequests[toolCall.toolCallId] = {\n                      type: \"tool-approval-request\",\n                      approvalId,\n                      toolCall,\n                      isAutomatic: true,\n                      ...signature != null ? { signature } : {}\n                    };\n                    stepToolApprovalResponses[toolCall.toolCallId] = {\n                      type: \"tool-approval-response\",\n                      approvalId,\n                      toolCall,\n                      approved: true,\n                      reason: toolApprovalStatus.reason,\n                      providerExecuted: toolCall.providerExecuted\n                    };\n                    break;\n                  }\n                  case \"denied\": {\n                    toolApprovalRequests[toolCall.toolCallId] = {\n                      type: \"tool-approval-request\",\n                      approvalId,\n                      toolCall,\n                      isAutomatic: true,\n                      ...signature != null ? { signature } : {}\n                    };\n                    stepToolApprovalResponses[toolCall.toolCallId] = {\n                      type: \"tool-approval-response\",\n                      approvalId,\n                      toolCall,\n                      approved: false,\n                      reason: toolApprovalStatus.reason,\n                      providerExecuted: toolCall.providerExecuted\n                    };\n                    blockedToolCallIds.add(toolCall.toolCallId);\n                    break;\n                  }\n                }\n              }\n              const invalidToolCalls = stepToolCalls.filter(\n                (toolCall) => toolCall.invalid && toolCall.dynamic\n              );\n              clientToolOutputs = [];\n              for (const toolCall of invalidToolCalls) {\n                clientToolOutputs.push({\n                  type: \"tool-error\",\n                  toolCallId: toolCall.toolCallId,\n                  toolName: toolCall.toolName,\n                  input: toolCall.input,\n                  error: getErrorMessage5(toolCall.error),\n                  dynamic: true\n                });\n              }\n              clientToolCalls = stepToolCalls.filter(\n                (toolCall) => !toolCall.providerExecuted\n              );\n              toolApprovalResponses = Object.values(stepToolApprovalResponses);\n              deniedToolApprovalResponses = toolApprovalResponses.filter(\n                (toolApprovalResponse) => toolApprovalResponse.approved === false\n              );\n              const toolExecutionMs = {};\n              if (tools != null) {\n                const toolExecutionResults = await executeTools({\n                  toolCalls: clientToolCalls.filter(\n                    (toolCall) => !toolCall.invalid && !blockedToolCallIds.has(toolCall.toolCallId)\n                  ),\n                  tools,\n                  callId,\n                  messages: stepMessages,\n                  abortSignal: mergedAbortSignal,\n                  timeout,\n                  experimental_sandbox: stepSandbox,\n                  toolsContext,\n                  onToolExecutionStart: (event) => notify({\n                    event,\n                    callbacks: [\n                      resolvedOnToolExecutionStart,\n                      telemetryDispatcher.onToolExecutionStart\n                    ]\n                  }),\n                  onToolExecutionEnd: (event) => notify({\n                    event,\n                    callbacks: [\n                      resolvedOnToolExecutionEnd,\n                      telemetryDispatcher.onToolExecutionEnd\n                    ]\n                  }),\n                  executeToolInTelemetryContext: telemetryDispatcher.executeTool,\n                  runInTracingChannelSpan\n                });\n                for (const result of toolExecutionResults) {\n                  toolExecutionMs[result.output.toolCallId] = result.toolExecutionMs;\n                  clientToolOutputs.push(result.output);\n                }\n              }\n              const stepTimeMs = now2() - stepStartTimestampMs;\n              const stepPerformance = {\n                effectiveOutputTokensPerSecond: calculateTokensPerSecond({\n                  tokens: stepUsage.outputTokens,\n                  durationMs: responseTimeMs\n                }),\n                outputTokensPerSecond: void 0,\n                inputTokensPerSecond: void 0,\n                effectiveTotalTokensPerSecond: calculateTokensPerSecond({\n                  tokens: sumTokenCounts(\n                    stepUsage.inputTokens,\n                    stepUsage.outputTokens\n                  ),\n                  durationMs: responseTimeMs\n                }),\n                stepTimeMs,\n                responseTimeMs,\n                toolExecutionMs,\n                timeToFirstOutputMs: void 0\n              };\n              for (const toolCall of stepToolCalls) {\n                if (!toolCall.providerExecuted)\n                  continue;\n                const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n                if ((tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults) {\n                  const hasResultInResponse = currentModelResponse.content.some(\n                    (part) => part.type === \"tool-result\" && part.toolCallId === toolCall.toolCallId\n                  );\n                  if (!hasResultInResponse) {\n                    pendingDeferredToolCalls.set(toolCall.toolCallId, {\n                      toolName: toolCall.toolName\n                    });\n                  }\n                }\n              }\n              for (const part of currentModelResponse.content) {\n                if (part.type === \"tool-result\") {\n                  pendingDeferredToolCalls.delete(part.toolCallId);\n                }\n              }\n              const stepContent = asContent({\n                content: currentModelResponse.content,\n                toolCalls: stepToolCalls,\n                toolOutputs: clientToolOutputs,\n                toolApprovalRequests: Object.values(toolApprovalRequests),\n                toolApprovalResponses,\n                tools\n              });\n              const stepResponseMessages = await toResponseMessages({\n                content: stepContent,\n                tools\n              });\n              const stepRequest = {\n                ...currentModelResponse.request,\n                body: include.requestBody ? (_o = currentModelResponse.request) == null ? void 0 : _o.body : void 0,\n                messages: include.requestMessages ? cloneModelMessages(stepMessages) : void 0\n              };\n              const stepResponse = {\n                ...currentModelResponse.response,\n                // deep clone msgs to avoid mutating step results in multi-step:\n                messages: cloneModelMessages(stepResponseMessages),\n                // Conditionally include response body:\n                body: include.responseBody ? (_p = currentModelResponse.response) == null ? void 0 : _p.body : void 0\n              };\n              const currentStepResult = new DefaultStepResult({\n                callId,\n                stepNumber,\n                provider: stepModel.provider,\n                modelId: stepModel.modelId,\n                runtimeContext,\n                content: stepContent,\n                finishReason: currentModelResponse.finishReason.unified,\n                rawFinishReason: currentModelResponse.finishReason.raw,\n                usage: stepUsage,\n                performance: stepPerformance,\n                warnings: currentModelResponse.warnings,\n                providerMetadata: currentModelResponse.providerMetadata,\n                request: stepRequest,\n                response: stepResponse,\n                toolsContext\n              });\n              logWarnings({\n                warnings: (_q = currentModelResponse.warnings) != null ? _q : [],\n                provider: stepModel.provider,\n                model: stepModel.modelId\n              });\n              steps.push(currentStepResult);\n              instructionsForNextStep = stepInstructions;\n              messagesForNextStep = [...stepMessages, ...stepResponseMessages];\n              await notify({\n                event: currentStepResult,\n                callbacks: [resolvedOnStepEnd, telemetryDispatcher.onStepEnd]\n              });\n              return currentStepResult;\n            }\n          });\n        } finally {\n          if (stepTimeoutId != null) {\n            clearTimeout(stepTimeoutId);\n          }\n        }\n      } while (\n        // Continue if:\n        // 1. There are client tool calls that have all been executed or denied, OR\n        // 2. There are pending deferred results from provider-executed tools\n        (clientToolCalls.length > 0 && clientToolOutputs.length + deniedToolApprovalResponses.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:\n        !await isStopConditionMet({ stopConditions, steps })\n      );\n      const lastStep = steps[steps.length - 1];\n      const totalUsage = steps.reduce(\n        (totalUsage2, step) => {\n          return addLanguageModelUsage(totalUsage2, step.usage);\n        },\n        {\n          inputTokens: void 0,\n          inputTokenDetails: {\n            noCacheTokens: void 0,\n            cacheReadTokens: void 0,\n            cacheWriteTokens: void 0\n          },\n          outputTokens: void 0,\n          outputTokenDetails: {\n            textTokens: void 0,\n            reasoningTokens: void 0\n          },\n          totalTokens: void 0\n        }\n      );\n      const files = steps.flatMap((step) => step.files);\n      const sources = steps.flatMap((step) => step.sources);\n      const toolCalls = steps.flatMap((step) => step.toolCalls);\n      const staticToolCalls = steps.flatMap((step) => step.staticToolCalls);\n      const dynamicToolCalls = steps.flatMap((step) => step.dynamicToolCalls);\n      const toolResults = steps.flatMap((step) => step.toolResults);\n      const staticToolResults = steps.flatMap((step) => step.staticToolResults);\n      const dynamicToolResults = steps.flatMap((step) => step.dynamicToolResults);\n      const warnings = steps.flatMap((step) => {\n        var _a24;\n        return (_a24 = step.warnings) != null ? _a24 : [];\n      });\n      const onEndEvent = {\n        callId,\n        stepNumber: lastStep.stepNumber,\n        model: lastStep.model,\n        runtimeContext: lastStep.runtimeContext,\n        finishReason: lastStep.finishReason,\n        rawFinishReason: lastStep.rawFinishReason,\n        usage: totalUsage,\n        totalUsage,\n        content: steps.flatMap((step) => step.content),\n        text: lastStep.text,\n        reasoning: lastStep.reasoning,\n        reasoningText: lastStep.reasoningText,\n        files,\n        sources,\n        toolCalls,\n        staticToolCalls,\n        dynamicToolCalls,\n        toolResults,\n        staticToolResults,\n        dynamicToolResults,\n        responseMessages: [\n          ...initialResponseMessages,\n          ...steps.flatMap((step) => step.response.messages)\n        ],\n        warnings,\n        request: lastStep.request,\n        response: lastStep.response,\n        providerMetadata: lastStep.providerMetadata,\n        steps,\n        finalStep: lastStep,\n        toolsContext\n      };\n      await notify({\n        event: onEndEvent,\n        callbacks: [onEnd, telemetryDispatcher.onEnd]\n      });\n      let resolvedOutput;\n      if (lastStep.finishReason === \"stop\") {\n        const outputSpecification = output != null ? output : text();\n        resolvedOutput = await outputSpecification.parseCompleteOutput(\n          { text: lastStep.text },\n          {\n            response: lastStep.response,\n            usage: lastStep.usage,\n            finishReason: lastStep.finishReason\n          }\n        );\n      }\n      return new DefaultGenerateTextResult({\n        initialResponseMessages,\n        steps,\n        totalUsage,\n        output: resolvedOutput\n      });\n    } catch (error) {\n      await ((_a23 = telemetryDispatcher.onError) == null ? void 0 : _a23.call(telemetryDispatcher, { callId, error }));\n      throw wrapGatewayError(error);\n    }\n  };\n  return await runInTracingChannelSpan({\n    type: \"generateText\",\n    event: generateTextStartEvent,\n    execute: executeGenerateText\n  });\n}\nasync function executeTools({\n  toolCalls,\n  tools,\n  callId,\n  messages,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  toolsContext,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  executeToolInTelemetryContext,\n  runInTracingChannelSpan\n}) {\n  const toolResults = await Promise.all(\n    toolCalls.map(\n      async (toolCall) => await executeToolCall({\n        toolCall,\n        tools,\n        callId,\n        messages,\n        abortSignal,\n        timeout,\n        experimental_sandbox: sandbox,\n        toolsContext,\n        onToolExecutionStart,\n        onToolExecutionEnd,\n        executeToolInTelemetryContext,\n        runInTracingChannelSpan\n      })\n    )\n  );\n  return toolResults.filter(\n    (result) => result != null\n  );\n}\nvar DefaultGenerateTextResult = class {\n  constructor(options) {\n    this.initialResponseMessages = options.initialResponseMessages;\n    this.steps = options.steps;\n    this._output = options.output;\n    this.totalUsage = options.totalUsage;\n  }\n  get finalStep() {\n    return this.steps.at(-1);\n  }\n  get content() {\n    return this.steps.flatMap((step) => step.content);\n  }\n  get text() {\n    return this.finalStep.text;\n  }\n  get files() {\n    return this.steps.flatMap((step) => step.files);\n  }\n  get reasoningText() {\n    return this.finalStep.reasoningText;\n  }\n  get reasoning() {\n    return convertToReasoningOutputs(this.finalStep.reasoning);\n  }\n  get toolCalls() {\n    return this.steps.flatMap((step) => step.toolCalls);\n  }\n  get staticToolCalls() {\n    return this.steps.flatMap((step) => step.staticToolCalls);\n  }\n  get dynamicToolCalls() {\n    return this.steps.flatMap((step) => step.dynamicToolCalls);\n  }\n  get toolResults() {\n    return this.steps.flatMap((step) => step.toolResults);\n  }\n  get staticToolResults() {\n    return this.steps.flatMap((step) => step.staticToolResults);\n  }\n  get dynamicToolResults() {\n    return this.steps.flatMap((step) => step.dynamicToolResults);\n  }\n  get sources() {\n    return this.steps.flatMap((step) => step.sources);\n  }\n  get finishReason() {\n    return this.finalStep.finishReason;\n  }\n  get rawFinishReason() {\n    return this.finalStep.rawFinishReason;\n  }\n  get warnings() {\n    return this.steps.flatMap((step) => {\n      var _a22;\n      return (_a22 = step.warnings) != null ? _a22 : [];\n    });\n  }\n  get providerMetadata() {\n    return this.finalStep.providerMetadata;\n  }\n  get response() {\n    return this.finalStep.response;\n  }\n  get responseMessages() {\n    return [\n      ...this.initialResponseMessages,\n      ...this.steps.flatMap((step) => step.response.messages)\n    ];\n  }\n  get request() {\n    return this.finalStep.request;\n  }\n  get usage() {\n    return this.totalUsage;\n  }\n  get output() {\n    if (this._output == null) {\n      throw new NoOutputGeneratedError();\n    }\n    return this._output;\n  }\n};\nfunction asContent({\n  content,\n  toolCalls,\n  toolOutputs,\n  toolApprovalRequests,\n  toolApprovalResponses,\n  tools\n}) {\n  const contentParts = [];\n  const toolOutputsWithApprovalResponses = [];\n  const toolOutputsWithoutApprovalResponses = [];\n  const toolCallIdsWithApprovalResponses = new Set(\n    toolApprovalResponses.map(\n      (toolApprovalResponse) => toolApprovalResponse.toolCall.toolCallId\n    )\n  );\n  for (const part of content) {\n    switch (part.type) {\n      case \"text\":\n      case \"reasoning\":\n      case \"custom\":\n      case \"source\":\n        contentParts.push(part);\n        break;\n      case \"file\":\n      case \"reasoning-file\": {\n        contentParts.push({\n          type: part.type,\n          file: new DefaultGeneratedFile({\n            data: part.data.type === \"data\" ? part.data.data : part.data.url.toString(),\n            mediaType: part.mediaType\n          }),\n          ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n        });\n        break;\n      }\n      case \"tool-call\": {\n        contentParts.push(\n          toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId)\n        );\n        break;\n      }\n      case \"tool-result\": {\n        const toolCall = toolCalls.find(\n          (toolCall2) => toolCall2.toolCallId === part.toolCallId\n        );\n        if (toolCall == null) {\n          const tool2 = tools == null ? void 0 : tools[part.toolName];\n          const supportsDeferredResults = (tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults;\n          if (!supportsDeferredResults) {\n            throw new Error(`Tool call ${part.toolCallId} not found.`);\n          }\n          if (part.isError) {\n            contentParts.push({\n              type: \"tool-error\",\n              toolCallId: part.toolCallId,\n              toolName: part.toolName,\n              input: void 0,\n              error: part.result,\n              providerExecuted: true,\n              dynamic: part.dynamic,\n              ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n              ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}\n            });\n          } else {\n            contentParts.push({\n              type: \"tool-result\",\n              toolCallId: part.toolCallId,\n              toolName: part.toolName,\n              input: void 0,\n              output: part.result,\n              providerExecuted: true,\n              dynamic: part.dynamic,\n              ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n              ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}\n            });\n          }\n          break;\n        }\n        if (part.isError) {\n          contentParts.push({\n            type: \"tool-error\",\n            toolCallId: part.toolCallId,\n            toolName: part.toolName,\n            input: toolCall.input,\n            error: part.result,\n            providerExecuted: true,\n            dynamic: toolCall.dynamic,\n            ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n            ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n          });\n        } else {\n          contentParts.push({\n            type: \"tool-result\",\n            toolCallId: part.toolCallId,\n            toolName: part.toolName,\n            input: toolCall.input,\n            output: part.result,\n            providerExecuted: true,\n            dynamic: toolCall.dynamic,\n            ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n            ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n          });\n        }\n        break;\n      }\n      case \"tool-approval-request\": {\n        const toolCall = toolCalls.find(\n          (toolCall2) => toolCall2.toolCallId === part.toolCallId\n        );\n        if (toolCall == null) {\n          throw new ToolCallNotFoundForApprovalError({\n            toolCallId: part.toolCallId,\n            approvalId: part.approvalId\n          });\n        }\n        contentParts.push({\n          type: \"tool-approval-request\",\n          approvalId: part.approvalId,\n          toolCall\n        });\n        break;\n      }\n    }\n  }\n  for (const toolOutput of toolOutputs) {\n    if (toolCallIdsWithApprovalResponses.has(toolOutput.toolCallId)) {\n      toolOutputsWithApprovalResponses.push(toolOutput);\n    } else {\n      toolOutputsWithoutApprovalResponses.push(toolOutput);\n    }\n  }\n  return [\n    ...contentParts,\n    ...toolOutputsWithoutApprovalResponses,\n    ...toolApprovalRequests,\n    ...toolApprovalResponses,\n    ...toolOutputsWithApprovalResponses\n  ];\n}\n\n// src/generate-text/stream-text.ts\nimport {\n  getErrorMessage as getErrorMessage7,\n  UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nimport {\n  asArray as asArray6,\n  createIdGenerator as createIdGenerator3,\n  DelayedPromise,\n  filterNullable as filterNullable2,\n  isAbortError as isAbortError2\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/prepare-headers.ts\nfunction prepareHeaders(headers, defaultHeaders) {\n  const responseHeaders = new Headers(headers != null ? headers : {});\n  for (const [key, value] of Object.entries(defaultHeaders)) {\n    if (!responseHeaders.has(key)) {\n      responseHeaders.set(key, value);\n    }\n  }\n  return responseHeaders;\n}\n\n// src/text-stream/create-text-stream-response.ts\nfunction createTextStreamResponse({\n  status,\n  statusText,\n  headers,\n  stream\n}) {\n  return new Response(stream.pipeThrough(new TextEncoderStream()), {\n    status: status != null ? status : 200,\n    statusText,\n    headers: prepareHeaders(headers, {\n      \"content-type\": \"text/plain; charset=utf-8\"\n    })\n  });\n}\n\n// src/util/write-to-server-response.ts\nfunction writeToServerResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream\n}) {\n  const statusCode = status != null ? status : 200;\n  if (statusText !== void 0) {\n    response.writeHead(statusCode, statusText, headers);\n  } else {\n    response.writeHead(statusCode, headers);\n  }\n  const reader = stream.getReader();\n  const read = async () => {\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done)\n          break;\n        const canContinue = response.write(value);\n        if (!canContinue) {\n          await new Promise((resolve3) => {\n            response.once(\"drain\", resolve3);\n          });\n        }\n      }\n    } catch (error) {\n      throw error;\n    } finally {\n      response.end();\n    }\n  };\n  read();\n}\n\n// src/text-stream/pipe-text-stream-to-response.ts\nfunction pipeTextStreamToResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream\n}) {\n  writeToServerResponse({\n    response,\n    status,\n    statusText,\n    headers: Object.fromEntries(\n      prepareHeaders(headers, {\n        \"content-type\": \"text/plain; charset=utf-8\"\n      }).entries()\n    ),\n    stream: stream.pipeThrough(new TextEncoderStream())\n  });\n}\n\n// src/text-stream/to-text-stream.ts\nfunction toTextStream({\n  stream\n}) {\n  return stream.pipeThrough(\n    new TransformStream({\n      transform(part, controller) {\n        if (part.type === \"text-delta\") {\n          controller.enqueue(part.text);\n        }\n      }\n    })\n  );\n}\n\n// src/ui-message-stream/json-to-sse-transform-stream.ts\nvar JsonToSseTransformStream = class extends TransformStream {\n  constructor() {\n    super({\n      transform(part, controller) {\n        controller.enqueue(`data: ${JSON.stringify(part)}\n\n`);\n      },\n      flush(controller) {\n        controller.enqueue(\"data: [DONE]\\n\\n\");\n      }\n    });\n  }\n};\n\n// src/ui-message-stream/ui-message-stream-headers.ts\nvar UI_MESSAGE_STREAM_HEADERS = {\n  \"content-type\": \"text/event-stream\",\n  \"cache-control\": \"no-cache\",\n  connection: \"keep-alive\",\n  \"x-vercel-ai-ui-message-stream\": \"v1\",\n  \"x-accel-buffering\": \"no\"\n  // disable nginx buffering\n};\n\n// src/ui-message-stream/create-ui-message-stream-response.ts\nfunction createUIMessageStreamResponse({\n  status,\n  statusText,\n  headers,\n  stream,\n  consumeSseStream\n}) {\n  let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n  if (consumeSseStream) {\n    const [stream1, stream2] = sseStream.tee();\n    sseStream = stream1;\n    consumeSseStream({ stream: stream2 });\n  }\n  return new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n    status,\n    statusText,\n    headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)\n  });\n}\n\n// src/ui-message-stream/pipe-ui-message-stream-to-response.ts\nfunction pipeUIMessageStreamToResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream,\n  consumeSseStream\n}) {\n  let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n  if (consumeSseStream) {\n    const [stream1, stream2] = sseStream.tee();\n    sseStream = stream1;\n    consumeSseStream({ stream: stream2 });\n  }\n  writeToServerResponse({\n    response,\n    status,\n    statusText,\n    headers: Object.fromEntries(\n      prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS).entries()\n    ),\n    stream: sseStream.pipeThrough(new TextEncoderStream())\n  });\n}\n\n// src/ui-message-stream/get-response-ui-message-id.ts\nfunction getResponseUIMessageId({\n  originalMessages,\n  responseMessageId\n}) {\n  if (originalMessages == null) {\n    return void 0;\n  }\n  const lastMessage = originalMessages[originalMessages.length - 1];\n  return (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage.id : typeof responseMessageId === \"function\" ? responseMessageId() : responseMessageId;\n}\n\n// src/ui/process-ui-message-stream.ts\nimport { validateTypes as validateTypes2 } from \"@ai-sdk/provider-utils\";\n\n// src/ui-message-stream/ui-message-chunks.ts\nimport { z as z6 } from \"zod/v4\";\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nvar toolMetadataSchema = z6.record(\n  z6.string(),\n  jsonValueSchema.optional()\n);\nvar uiMessageChunkSchema = lazySchema(\n  () => zodSchema(\n    z6.union([\n      z6.strictObject({\n        type: z6.literal(\"text-start\"),\n        id: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"text-delta\"),\n        id: z6.string(),\n        delta: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"text-end\"),\n        id: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"error\"),\n        errorText: z6.string()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-input-start\"),\n        toolCallId: z6.string(),\n        toolName: z6.string(),\n        providerExecuted: z6.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z6.boolean().optional(),\n        title: z6.string().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-input-delta\"),\n        toolCallId: z6.string(),\n        inputTextDelta: z6.string()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-input-available\"),\n        toolCallId: z6.string(),\n        toolName: z6.string(),\n        input: z6.unknown(),\n        providerExecuted: z6.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z6.boolean().optional(),\n        title: z6.string().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-input-error\"),\n        toolCallId: z6.string(),\n        toolName: z6.string(),\n        input: z6.unknown(),\n        providerExecuted: z6.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z6.boolean().optional(),\n        errorText: z6.string(),\n        title: z6.string().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-approval-request\"),\n        approvalId: z6.string(),\n        toolCallId: z6.string(),\n        isAutomatic: z6.boolean().optional(),\n        signature: z6.string().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-approval-response\"),\n        approvalId: z6.string(),\n        approved: z6.boolean(),\n        reason: z6.string().optional(),\n        providerExecuted: z6.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-output-available\"),\n        toolCallId: z6.string(),\n        output: z6.unknown(),\n        providerExecuted: z6.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z6.boolean().optional(),\n        preliminary: z6.boolean().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-output-error\"),\n        toolCallId: z6.string(),\n        errorText: z6.string(),\n        providerExecuted: z6.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z6.boolean().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"tool-output-denied\"),\n        toolCallId: z6.string()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"reasoning-start\"),\n        id: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"reasoning-delta\"),\n        id: z6.string(),\n        delta: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"reasoning-end\"),\n        id: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"custom\"),\n        kind: z6.string().transform((value) => value),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"source-url\"),\n        sourceId: z6.string(),\n        url: z6.string(),\n        title: z6.string().optional(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"source-document\"),\n        sourceId: z6.string(),\n        mediaType: z6.string(),\n        title: z6.string(),\n        filename: z6.string().optional(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"file\"),\n        url: z6.string(),\n        mediaType: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"reasoning-file\"),\n        url: z6.string(),\n        mediaType: z6.string(),\n        providerMetadata: providerMetadataSchema.optional()\n      }),\n      z6.strictObject({\n        type: z6.custom(\n          (value) => typeof value === \"string\" && value.startsWith(\"data-\"),\n          { message: 'Type must start with \"data-\"' }\n        ),\n        id: z6.string().optional(),\n        data: z6.unknown(),\n        transient: z6.boolean().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"start-step\")\n      }),\n      z6.strictObject({\n        type: z6.literal(\"finish-step\")\n      }),\n      z6.strictObject({\n        type: z6.literal(\"start\"),\n        messageId: z6.string().optional(),\n        messageMetadata: z6.unknown().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"finish\"),\n        finishReason: z6.enum([\n          \"stop\",\n          \"length\",\n          \"content-filter\",\n          \"tool-calls\",\n          \"error\",\n          \"other\"\n        ]).optional(),\n        messageMetadata: z6.unknown().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"abort\"),\n        reason: z6.string().optional()\n      }),\n      z6.strictObject({\n        type: z6.literal(\"message-metadata\"),\n        messageMetadata: z6.unknown()\n      })\n    ])\n  )\n);\nfunction isDataUIMessageChunk(chunk) {\n  return chunk.type.startsWith(\"data-\");\n}\n\n// src/util/create-id-map.ts\nfunction createIdMap() {\n  return /* @__PURE__ */ Object.create(null);\n}\n\n// src/ui/ui-messages.ts\nfunction isDataUIPart(part) {\n  return part.type.startsWith(\"data-\");\n}\nfunction isTextUIPart(part) {\n  return part.type === \"text\";\n}\nfunction isCustomContentUIPart(part) {\n  return part.type === \"custom\";\n}\nfunction isFileUIPart(part) {\n  return part.type === \"file\";\n}\nfunction isReasoningFileUIPart(part) {\n  return part.type === \"reasoning-file\";\n}\nfunction isReasoningUIPart(part) {\n  return part.type === \"reasoning\";\n}\nfunction isStaticToolUIPart(part) {\n  return part.type.startsWith(\"tool-\");\n}\nfunction isDynamicToolUIPart(part) {\n  return part.type === \"dynamic-tool\";\n}\nfunction isToolUIPart(part) {\n  return isStaticToolUIPart(part) || isDynamicToolUIPart(part);\n}\nfunction getStaticToolName(part) {\n  return part.type.split(\"-\").slice(1).join(\"-\");\n}\nfunction getToolName(part) {\n  return isDynamicToolUIPart(part) ? part.toolName : getStaticToolName(part);\n}\nvar getToolOrDynamicToolName = getToolName;\n\n// src/ui/process-ui-message-stream.ts\nfunction createStreamingUIMessageState({\n  lastMessage,\n  messageId\n}) {\n  return {\n    message: (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage : {\n      id: messageId,\n      metadata: void 0,\n      role: \"assistant\",\n      parts: []\n    },\n    activeTextParts: createIdMap(),\n    activeReasoningParts: createIdMap(),\n    partialToolCalls: createIdMap()\n  };\n}\nfunction processUIMessageStream({\n  stream,\n  messageMetadataSchema,\n  dataPartSchemas,\n  runUpdateMessageJob,\n  onError,\n  onToolCall,\n  onData\n}) {\n  return stream.pipeThrough(\n    new TransformStream({\n      async transform(chunk, controller) {\n        await runUpdateMessageJob(async ({ state, write }) => {\n          var _a22, _b, _c, _d;\n          function getToolInvocation(toolCallId) {\n            const toolInvocations = state.message.parts.filter(isToolUIPart);\n            const toolInvocation = toolInvocations.find(\n              (invocation) => invocation.toolCallId === toolCallId\n            );\n            if (toolInvocation == null) {\n              throw new UIMessageStreamError({\n                chunkType: \"tool-invocation\",\n                chunkId: toolCallId,\n                message: `No tool invocation found for tool call ID \"${toolCallId}\".`\n              });\n            }\n            return toolInvocation;\n          }\n          function getToolInvocationByApprovalId(approvalId) {\n            const toolInvocations = state.message.parts.filter(isToolUIPart);\n            const toolInvocation = toolInvocations.find(\n              (invocation) => {\n                var _a23;\n                return ((_a23 = invocation.approval) == null ? void 0 : _a23.id) === approvalId;\n              }\n            );\n            if (toolInvocation == null) {\n              throw new UIMessageStreamError({\n                chunkType: \"tool-approval-response\",\n                chunkId: approvalId,\n                message: `No tool invocation found for approval ID \"${approvalId}\".`\n              });\n            }\n            return toolInvocation;\n          }\n          function updateToolPart(options) {\n            var _a23;\n            const part = state.message.parts.find(\n              (part2) => isStaticToolUIPart(part2) && part2.toolCallId === options.toolCallId\n            );\n            const anyOptions = options;\n            const anyPart = part;\n            if (part != null) {\n              part.state = options.state;\n              anyPart.input = anyOptions.input;\n              anyPart.output = anyOptions.output;\n              anyPart.errorText = anyOptions.errorText;\n              anyPart.rawInput = anyOptions.rawInput;\n              anyPart.preliminary = anyOptions.preliminary;\n              if (options.title !== void 0) {\n                anyPart.title = options.title;\n              }\n              if (options.toolMetadata !== void 0) {\n                anyPart.toolMetadata = options.toolMetadata;\n              }\n              anyPart.providerExecuted = (_a23 = anyOptions.providerExecuted) != null ? _a23 : part.providerExecuted;\n              const providerMetadata = anyOptions.providerMetadata;\n              if (providerMetadata != null) {\n                if (options.state === \"output-available\" || options.state === \"output-error\") {\n                  const resultPart = part;\n                  resultPart.resultProviderMetadata = providerMetadata;\n                } else {\n                  part.callProviderMetadata = providerMetadata;\n                }\n              }\n            } else {\n              state.message.parts.push({\n                type: `tool-${options.toolName}`,\n                toolCallId: options.toolCallId,\n                state: options.state,\n                title: options.title,\n                ...options.toolMetadata !== void 0 ? { toolMetadata: options.toolMetadata } : {},\n                input: anyOptions.input,\n                output: anyOptions.output,\n                rawInput: anyOptions.rawInput,\n                errorText: anyOptions.errorText,\n                providerExecuted: anyOptions.providerExecuted,\n                preliminary: anyOptions.preliminary,\n                ...anyOptions.providerMetadata != null && (options.state === \"output-available\" || options.state === \"output-error\") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},\n                ...anyOptions.providerMetadata != null && !(options.state === \"output-available\" || options.state === \"output-error\") ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n              });\n            }\n          }\n          function updateDynamicToolPart(options) {\n            var _a23, _b2;\n            const part = state.message.parts.find(\n              (part2) => part2.type === \"dynamic-tool\" && part2.toolCallId === options.toolCallId\n            );\n            const anyOptions = options;\n            const anyPart = part;\n            if (part != null) {\n              part.state = options.state;\n              anyPart.toolName = options.toolName;\n              anyPart.input = anyOptions.input;\n              anyPart.output = anyOptions.output;\n              anyPart.errorText = anyOptions.errorText;\n              anyPart.rawInput = (_a23 = anyOptions.rawInput) != null ? _a23 : anyPart.rawInput;\n              anyPart.preliminary = anyOptions.preliminary;\n              if (options.title !== void 0) {\n                anyPart.title = options.title;\n              }\n              if (options.toolMetadata !== void 0) {\n                anyPart.toolMetadata = options.toolMetadata;\n              }\n              anyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;\n              const providerMetadata = anyOptions.providerMetadata;\n              if (providerMetadata != null) {\n                if (options.state === \"output-available\" || options.state === \"output-error\") {\n                  const resultPart = part;\n                  resultPart.resultProviderMetadata = providerMetadata;\n                } else {\n                  part.callProviderMetadata = providerMetadata;\n                }\n              }\n            } else {\n              state.message.parts.push({\n                type: \"dynamic-tool\",\n                toolName: options.toolName,\n                toolCallId: options.toolCallId,\n                state: options.state,\n                input: anyOptions.input,\n                output: anyOptions.output,\n                errorText: anyOptions.errorText,\n                preliminary: anyOptions.preliminary,\n                providerExecuted: anyOptions.providerExecuted,\n                title: options.title,\n                ...options.toolMetadata !== void 0 ? { toolMetadata: options.toolMetadata } : {},\n                ...anyOptions.providerMetadata != null && (options.state === \"output-available\" || options.state === \"output-error\") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},\n                ...anyOptions.providerMetadata != null && !(options.state === \"output-available\" || options.state === \"output-error\") ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n              });\n            }\n          }\n          async function updateMessageMetadata(metadata) {\n            if (metadata != null) {\n              const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;\n              if (messageMetadataSchema != null) {\n                await validateTypes2({\n                  value: mergedMetadata,\n                  schema: messageMetadataSchema,\n                  context: {\n                    field: \"message.metadata\",\n                    entityId: state.message.id\n                  }\n                });\n              }\n              state.message.metadata = mergedMetadata;\n            }\n          }\n          switch (chunk.type) {\n            case \"text-start\": {\n              const textPart = {\n                type: \"text\",\n                text: \"\",\n                providerMetadata: chunk.providerMetadata,\n                state: \"streaming\"\n              };\n              state.activeTextParts[chunk.id] = textPart;\n              state.message.parts.push(textPart);\n              write();\n              break;\n            }\n            case \"text-delta\": {\n              const textPart = state.activeTextParts[chunk.id];\n              if (textPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: \"text-delta\",\n                  chunkId: chunk.id,\n                  message: `Received text-delta for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-delta\" chunks.`\n                });\n              }\n              textPart.text += chunk.delta;\n              textPart.providerMetadata = (_a22 = chunk.providerMetadata) != null ? _a22 : textPart.providerMetadata;\n              write();\n              break;\n            }\n            case \"text-end\": {\n              const textPart = state.activeTextParts[chunk.id];\n              if (textPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: \"text-end\",\n                  chunkId: chunk.id,\n                  message: `Received text-end for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-end\" chunks.`\n                });\n              }\n              textPart.state = \"done\";\n              textPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;\n              delete state.activeTextParts[chunk.id];\n              write();\n              break;\n            }\n            case \"custom\": {\n              const customPart = {\n                type: \"custom\",\n                kind: chunk.kind,\n                providerMetadata: chunk.providerMetadata\n              };\n              state.message.parts.push(customPart);\n              write();\n              break;\n            }\n            case \"reasoning-start\": {\n              const reasoningPart = {\n                type: \"reasoning\",\n                text: \"\",\n                providerMetadata: chunk.providerMetadata,\n                state: \"streaming\"\n              };\n              state.activeReasoningParts[chunk.id] = reasoningPart;\n              state.message.parts.push(reasoningPart);\n              write();\n              break;\n            }\n            case \"reasoning-delta\": {\n              const reasoningPart = state.activeReasoningParts[chunk.id];\n              if (reasoningPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: \"reasoning-delta\",\n                  chunkId: chunk.id,\n                  message: `Received reasoning-delta for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-delta\" chunks.`\n                });\n              }\n              reasoningPart.text += chunk.delta;\n              reasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;\n              write();\n              break;\n            }\n            case \"reasoning-end\": {\n              const reasoningPart = state.activeReasoningParts[chunk.id];\n              if (reasoningPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: \"reasoning-end\",\n                  chunkId: chunk.id,\n                  message: `Received reasoning-end for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-end\" chunks.`\n                });\n              }\n              reasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;\n              reasoningPart.state = \"done\";\n              delete state.activeReasoningParts[chunk.id];\n              write();\n              break;\n            }\n            case \"file\":\n            case \"reasoning-file\": {\n              state.message.parts.push({\n                type: chunk.type,\n                mediaType: chunk.mediaType,\n                url: chunk.url,\n                ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n              });\n              write();\n              break;\n            }\n            case \"source-url\": {\n              state.message.parts.push({\n                type: \"source-url\",\n                sourceId: chunk.sourceId,\n                url: chunk.url,\n                title: chunk.title,\n                providerMetadata: chunk.providerMetadata\n              });\n              write();\n              break;\n            }\n            case \"source-document\": {\n              state.message.parts.push({\n                type: \"source-document\",\n                sourceId: chunk.sourceId,\n                mediaType: chunk.mediaType,\n                title: chunk.title,\n                filename: chunk.filename,\n                providerMetadata: chunk.providerMetadata\n              });\n              write();\n              break;\n            }\n            case \"tool-input-start\": {\n              const toolInvocations = state.message.parts.filter(isStaticToolUIPart);\n              state.partialToolCalls[chunk.toolCallId] = {\n                text: \"\",\n                toolName: chunk.toolName,\n                index: toolInvocations.length,\n                dynamic: chunk.dynamic,\n                title: chunk.title,\n                toolMetadata: chunk.toolMetadata\n              };\n              if (chunk.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: \"input-streaming\",\n                  input: void 0,\n                  providerExecuted: chunk.providerExecuted,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                  providerMetadata: chunk.providerMetadata\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: \"input-streaming\",\n                  input: void 0,\n                  providerExecuted: chunk.providerExecuted,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                  providerMetadata: chunk.providerMetadata\n                });\n              }\n              write();\n              break;\n            }\n            case \"tool-input-delta\": {\n              const partialToolCall = state.partialToolCalls[chunk.toolCallId];\n              if (partialToolCall == null) {\n                throw new UIMessageStreamError({\n                  chunkType: \"tool-input-delta\",\n                  chunkId: chunk.toolCallId,\n                  message: `Received tool-input-delta for missing tool call with ID \"${chunk.toolCallId}\". Ensure a \"tool-input-start\" chunk is sent before any \"tool-input-delta\" chunks.`\n                });\n              }\n              partialToolCall.text += chunk.inputTextDelta;\n              const { value: partialArgs } = await parsePartialJson(\n                partialToolCall.text\n              );\n              if (partialToolCall.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: partialToolCall.toolName,\n                  state: \"input-streaming\",\n                  input: partialArgs,\n                  title: partialToolCall.title,\n                  toolMetadata: partialToolCall.toolMetadata\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: partialToolCall.toolName,\n                  state: \"input-streaming\",\n                  input: partialArgs,\n                  title: partialToolCall.title,\n                  toolMetadata: partialToolCall.toolMetadata\n                });\n              }\n              write();\n              break;\n            }\n            case \"tool-input-available\": {\n              if (chunk.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: \"input-available\",\n                  input: chunk.input,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: \"input-available\",\n                  input: chunk.input,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata\n                });\n              }\n              write();\n              if (onToolCall && !chunk.providerExecuted) {\n                await onToolCall({\n                  toolCall: chunk\n                });\n              }\n              break;\n            }\n            case \"tool-input-error\": {\n              const existingPart = state.message.parts.filter(isToolUIPart).find((p) => p.toolCallId === chunk.toolCallId);\n              const isDynamic = existingPart != null ? existingPart.type === \"dynamic-tool\" : !!chunk.dynamic;\n              if (isDynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: \"output-error\",\n                  input: chunk.input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  toolMetadata: chunk.toolMetadata\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: \"output-error\",\n                  input: void 0,\n                  rawInput: chunk.input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  toolMetadata: chunk.toolMetadata\n                });\n              }\n              write();\n              break;\n            }\n            case \"tool-approval-request\": {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              toolInvocation.state = \"approval-requested\";\n              toolInvocation.approval = {\n                id: chunk.approvalId,\n                ...chunk.isAutomatic === true ? { isAutomatic: true } : {},\n                ...chunk.signature != null ? { signature: chunk.signature } : {}\n              };\n              write();\n              break;\n            }\n            case \"tool-approval-response\": {\n              const toolInvocation = getToolInvocationByApprovalId(\n                chunk.approvalId\n              );\n              const approval = toolInvocation.approval == null ? { id: chunk.approvalId } : toolInvocation.approval;\n              toolInvocation.state = \"approval-responded\";\n              toolInvocation.approval = {\n                id: chunk.approvalId,\n                approved: chunk.approved,\n                ...chunk.reason != null ? { reason: chunk.reason } : {},\n                ...approval.isAutomatic === true ? { isAutomatic: true } : {}\n              };\n              if (chunk.providerExecuted != null) {\n                toolInvocation.providerExecuted = chunk.providerExecuted;\n              }\n              if (chunk.providerMetadata != null) {\n                toolInvocation.callProviderMetadata = chunk.providerMetadata;\n              }\n              write();\n              break;\n            }\n            case \"tool-output-denied\": {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              toolInvocation.state = \"output-denied\";\n              write();\n              break;\n            }\n            case \"tool-output-available\": {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              if (toolInvocation.type === \"dynamic-tool\") {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: toolInvocation.toolName,\n                  state: \"output-available\",\n                  input: toolInvocation.input,\n                  output: chunk.output,\n                  preliminary: chunk.preliminary,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: getStaticToolName(toolInvocation),\n                  state: \"output-available\",\n                  input: toolInvocation.input,\n                  output: chunk.output,\n                  providerExecuted: chunk.providerExecuted,\n                  preliminary: chunk.preliminary,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata\n                });\n              }\n              write();\n              break;\n            }\n            case \"tool-output-error\": {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              if (toolInvocation.type === \"dynamic-tool\") {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: toolInvocation.toolName,\n                  state: \"output-error\",\n                  input: toolInvocation.input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: getStaticToolName(toolInvocation),\n                  state: \"output-error\",\n                  input: toolInvocation.input,\n                  rawInput: toolInvocation.rawInput,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: toolInvocation.title,\n                  toolMetadata: toolInvocation.toolMetadata\n                });\n              }\n              write();\n              break;\n            }\n            case \"start-step\": {\n              state.message.parts.push({ type: \"step-start\" });\n              break;\n            }\n            case \"finish-step\": {\n              state.activeTextParts = createIdMap();\n              state.activeReasoningParts = createIdMap();\n              break;\n            }\n            case \"start\": {\n              if (chunk.messageId != null) {\n                state.message.id = chunk.messageId;\n              }\n              await updateMessageMetadata(chunk.messageMetadata);\n              if (chunk.messageId != null || chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n            case \"finish\": {\n              if (chunk.finishReason != null) {\n                state.finishReason = chunk.finishReason;\n              }\n              await updateMessageMetadata(chunk.messageMetadata);\n              if (chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n            case \"message-metadata\": {\n              await updateMessageMetadata(chunk.messageMetadata);\n              if (chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n            case \"error\": {\n              onError == null ? void 0 : onError(new Error(chunk.errorText));\n              break;\n            }\n            default: {\n              if (isDataUIMessageChunk(chunk)) {\n                if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {\n                  const partIdx = state.message.parts.findIndex(\n                    (p) => \"id\" in p && \"data\" in p && p.id === chunk.id && p.type === chunk.type\n                  );\n                  const actualPartIdx = partIdx >= 0 ? partIdx : state.message.parts.length;\n                  await validateTypes2({\n                    value: chunk.data,\n                    schema: dataPartSchemas[chunk.type],\n                    context: {\n                      field: `message.parts[${actualPartIdx}].data`,\n                      entityName: chunk.type,\n                      entityId: chunk.id\n                    }\n                  });\n                }\n                const dataChunk = chunk;\n                if (dataChunk.transient) {\n                  onData == null ? void 0 : onData(dataChunk);\n                  break;\n                }\n                const existingUIPart = dataChunk.id != null ? state.message.parts.find(\n                  (chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id\n                ) : void 0;\n                if (existingUIPart != null) {\n                  existingUIPart.data = dataChunk.data;\n                } else {\n                  state.message.parts.push(dataChunk);\n                }\n                onData == null ? void 0 : onData(dataChunk);\n                write();\n              }\n            }\n          }\n          controller.enqueue(chunk);\n        });\n      }\n    })\n  );\n}\n\n// src/ui-message-stream/handle-ui-message-stream-finish.ts\nfunction handleUIMessageStreamFinish({\n  messageId,\n  originalMessages = [],\n  onStepEnd,\n  onStepFinish,\n  onEnd,\n  onFinish,\n  onError,\n  stream\n}) {\n  let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];\n  if ((lastMessage == null ? void 0 : lastMessage.role) !== \"assistant\") {\n    lastMessage = void 0;\n  } else {\n    messageId = lastMessage.id;\n  }\n  let isAborted = false;\n  const idInjectedStream = stream.pipeThrough(\n    new TransformStream({\n      transform(chunk, controller) {\n        if (chunk.type === \"start\") {\n          const startChunk = chunk;\n          if (startChunk.messageId == null && messageId != null) {\n            startChunk.messageId = messageId;\n          }\n        }\n        if (chunk.type === \"abort\") {\n          isAborted = true;\n        }\n        controller.enqueue(chunk);\n      }\n    })\n  );\n  const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish;\n  const resolvedOnEnd = onEnd != null ? onEnd : onFinish;\n  if (resolvedOnEnd == null && resolvedOnStepEnd == null) {\n    return idInjectedStream;\n  }\n  const state = createStreamingUIMessageState({\n    lastMessage: lastMessage ? structuredClone(lastMessage) : void 0,\n    messageId: messageId != null ? messageId : \"\"\n    // will be overridden by the stream\n  });\n  const runUpdateMessageJob = async (job) => {\n    await job({ state, write: () => {\n    } });\n  };\n  let finishCalled = false;\n  const callOnEnd = async () => {\n    if (finishCalled || !resolvedOnEnd) {\n      return;\n    }\n    finishCalled = true;\n    const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n    await resolvedOnEnd({\n      isAborted,\n      isContinuation,\n      responseMessage: state.message,\n      messages: [\n        ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,\n        state.message\n      ],\n      finishReason: state.finishReason\n    });\n  };\n  const callOnStepFinish = async () => {\n    if (!resolvedOnStepEnd) {\n      return;\n    }\n    const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n    try {\n      await resolvedOnStepEnd({\n        isContinuation,\n        responseMessage: structuredClone(state.message),\n        messages: [\n          ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,\n          structuredClone(state.message)\n        ]\n      });\n    } catch (error) {\n      onError(error);\n    }\n  };\n  return processUIMessageStream({\n    stream: idInjectedStream,\n    runUpdateMessageJob,\n    onError\n  }).pipeThrough(\n    new TransformStream({\n      async transform(chunk, controller) {\n        if (chunk.type === \"finish-step\") {\n          await callOnStepFinish();\n        }\n        controller.enqueue(chunk);\n      },\n      // @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility\n      async cancel() {\n        await callOnEnd();\n      },\n      async flush() {\n        await callOnEnd();\n      }\n    })\n  );\n}\n\n// src/ui-message-stream/to-ui-message-chunk.ts\nfunction toUIMessageChunk(part, {\n  tools,\n  sendReasoning = true,\n  sendSources = false,\n  sendStart = true,\n  sendFinish = true,\n  onError = () => \"An error occurred.\",\n  // prevent leaking server error details to the client by default\n  messageMetadata,\n  responseMessageId\n} = {}) {\n  const isDynamic = (toolPart) => {\n    const tool2 = tools == null ? void 0 : tools[toolPart.toolName];\n    if (tool2 == null) {\n      return toolPart.dynamic;\n    }\n    return (tool2 == null ? void 0 : tool2.type) === \"dynamic\" ? true : void 0;\n  };\n  const partType = part.type;\n  switch (partType) {\n    case \"text-start\": {\n      return {\n        type: \"text-start\",\n        id: part.id,\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n      };\n    }\n    case \"text-delta\": {\n      return {\n        type: \"text-delta\",\n        id: part.id,\n        delta: part.text,\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n      };\n    }\n    case \"text-end\": {\n      return {\n        type: \"text-end\",\n        id: part.id,\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n      };\n    }\n    case \"reasoning-start\":\n    case \"reasoning-end\": {\n      if (!sendReasoning) {\n        return void 0;\n      }\n      return {\n        type: partType,\n        id: part.id,\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n      };\n    }\n    case \"reasoning-delta\": {\n      if (!sendReasoning) {\n        return void 0;\n      }\n      return {\n        type: \"reasoning-delta\",\n        id: part.id,\n        delta: part.text,\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n      };\n    }\n    case \"file\":\n    case \"reasoning-file\": {\n      if (partType === \"reasoning-file\" && !sendReasoning) {\n        return void 0;\n      }\n      return {\n        type: part.type,\n        mediaType: part.file.mediaType,\n        url: `data:${part.file.mediaType};base64,${part.file.base64}`,\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n      };\n    }\n    case \"source\": {\n      if (!sendSources) {\n        return void 0;\n      }\n      if (part.sourceType === \"url\") {\n        return {\n          type: \"source-url\",\n          sourceId: part.id,\n          url: part.url,\n          title: part.title,\n          ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n        };\n      }\n      if (part.sourceType === \"document\") {\n        return {\n          type: \"source-document\",\n          sourceId: part.id,\n          mediaType: part.mediaType,\n          title: part.title,\n          filename: part.filename,\n          ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n        };\n      }\n      return void 0;\n    }\n    case \"custom\": {\n      return {\n        type: \"custom\",\n        kind: part.kind,\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n      };\n    }\n    case \"tool-input-start\": {\n      const dynamic = isDynamic(part);\n      return {\n        type: \"tool-input-start\",\n        toolCallId: part.id,\n        toolName: part.toolName,\n        ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n        ...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n        ...dynamic != null ? { dynamic } : {},\n        ...part.title != null ? { title: part.title } : {}\n      };\n    }\n    case \"tool-input-delta\": {\n      return {\n        type: \"tool-input-delta\",\n        toolCallId: part.id,\n        inputTextDelta: part.delta\n      };\n    }\n    case \"tool-call\": {\n      const dynamic = isDynamic(part);\n      if (part.invalid) {\n        return {\n          type: \"tool-input-error\",\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          input: part.input,\n          ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n          ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n          ...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n          ...dynamic != null ? { dynamic } : {},\n          errorText: onError(part.error),\n          ...part.title != null ? { title: part.title } : {}\n        };\n      }\n      return {\n        type: \"tool-input-available\",\n        toolCallId: part.toolCallId,\n        toolName: part.toolName,\n        input: part.input,\n        ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n        ...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n        ...dynamic != null ? { dynamic } : {},\n        ...part.title != null ? { title: part.title } : {}\n      };\n    }\n    case \"tool-approval-request\": {\n      return {\n        type: \"tool-approval-request\",\n        approvalId: part.approvalId,\n        toolCallId: part.toolCall.toolCallId,\n        ...part.isAutomatic != null ? { isAutomatic: part.isAutomatic } : {},\n        ...part.signature != null ? { signature: part.signature } : {}\n      };\n    }\n    case \"tool-approval-response\": {\n      return {\n        type: \"tool-approval-response\",\n        approvalId: part.approvalId,\n        approved: part.approved,\n        ...part.reason != null ? { reason: part.reason } : {},\n        ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {}\n      };\n    }\n    case \"tool-result\": {\n      const dynamic = isDynamic(part);\n      return {\n        type: \"tool-output-available\",\n        toolCallId: part.toolCallId,\n        // UI stream chunks are serialized as JSON, which drops undefined\n        // properties. Use null so tool outputs always keep the output field.\n        output: part.output === void 0 ? null : part.output,\n        ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n        ...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n        ...part.preliminary != null ? { preliminary: part.preliminary } : {},\n        ...dynamic != null ? { dynamic } : {}\n      };\n    }\n    case \"tool-error\": {\n      const dynamic = isDynamic(part);\n      return {\n        type: \"tool-output-error\",\n        toolCallId: part.toolCallId,\n        errorText: part.providerExecuted ? typeof part.error === \"string\" ? part.error : JSON.stringify(part.error) : onError(part.error),\n        ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n        ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n        ...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n        ...dynamic != null ? { dynamic } : {}\n      };\n    }\n    case \"tool-output-denied\": {\n      return {\n        type: \"tool-output-denied\",\n        toolCallId: part.toolCallId\n      };\n    }\n    case \"error\": {\n      return {\n        type: \"error\",\n        errorText: onError(part.error)\n      };\n    }\n    case \"start-step\": {\n      return { type: \"start-step\" };\n    }\n    case \"finish-step\": {\n      return { type: \"finish-step\" };\n    }\n    case \"start\": {\n      if (!sendStart) {\n        return void 0;\n      }\n      return {\n        type: \"start\",\n        ...messageMetadata != null ? { messageMetadata } : {},\n        ...responseMessageId != null ? { messageId: responseMessageId } : {}\n      };\n    }\n    case \"finish\": {\n      if (!sendFinish) {\n        return void 0;\n      }\n      return {\n        type: \"finish\",\n        finishReason: part.finishReason,\n        ...messageMetadata != null ? { messageMetadata } : {}\n      };\n    }\n    case \"abort\": {\n      return part;\n    }\n    case \"tool-input-end\":\n    case \"raw\": {\n      return void 0;\n    }\n    default: {\n      const exhaustiveCheck = partType;\n      throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n    }\n  }\n}\n\n// src/ui-message-stream/to-ui-message-stream.ts\nfunction toUIMessageStream({\n  stream,\n  tools,\n  sendReasoning = true,\n  sendSources = false,\n  sendStart = true,\n  sendFinish = true,\n  onError = () => \"An error occurred.\",\n  // prevent leaking server error details to the client by default\n  messageMetadata,\n  originalMessages,\n  generateMessageId,\n  onEnd,\n  onFinish\n}) {\n  const responseMessageId = generateMessageId != null ? getResponseUIMessageId({\n    originalMessages,\n    responseMessageId: generateMessageId\n  }) : void 0;\n  const uiMessageChunkStream = stream.pipeThrough(\n    new TransformStream({\n      transform: async (part, controller) => {\n        const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });\n        const uiMessageChunk = toUIMessageChunk(part, {\n          tools,\n          sendReasoning,\n          sendSources,\n          sendStart,\n          sendFinish,\n          onError,\n          messageMetadata: messageMetadataValue,\n          responseMessageId\n        });\n        if (uiMessageChunk != null) {\n          controller.enqueue(uiMessageChunk);\n        }\n        if (messageMetadataValue != null && part.type !== \"start\" && part.type !== \"finish\") {\n          controller.enqueue({\n            type: \"message-metadata\",\n            messageMetadata: messageMetadataValue\n          });\n        }\n      }\n    })\n  );\n  return handleUIMessageStreamFinish({\n    stream: uiMessageChunkStream,\n    messageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),\n    originalMessages,\n    onEnd: onEnd != null ? onEnd : onFinish,\n    onError\n  });\n}\n\n// src/util/async-iterable-stream.ts\nfunction createAsyncIterableStream(source) {\n  const stream = source.pipeThrough(new TransformStream());\n  stream[Symbol.asyncIterator] = function() {\n    const reader = this.getReader();\n    let finished = false;\n    async function cleanup(cancelStream) {\n      var _a22;\n      if (finished)\n        return;\n      finished = true;\n      try {\n        if (cancelStream) {\n          await ((_a22 = reader.cancel) == null ? void 0 : _a22.call(reader));\n        }\n      } finally {\n        try {\n          reader.releaseLock();\n        } catch (e) {\n        }\n      }\n    }\n    return {\n      /**\n       * Reads the next chunk from the stream.\n       * @returns A promise resolving to the next IteratorResult.\n       */\n      async next() {\n        if (finished) {\n          return { done: true, value: void 0 };\n        }\n        const { done, value } = await reader.read();\n        if (done) {\n          await cleanup(true);\n          return { done: true, value: void 0 };\n        }\n        return { done: false, value };\n      },\n      /**\n       * May be called on early exit (e.g., break from for-await) or after completion.\n       * Ensures the stream is cancelled and resources are released.\n       * @returns A promise resolving to a completed IteratorResult.\n       */\n      async return() {\n        await cleanup(true);\n        return { done: true, value: void 0 };\n      },\n      /**\n       * Called on early exit with error.\n       * Ensures the stream is cancelled and resources are released, then rethrows the error.\n       * @param err The error to throw.\n       * @returns A promise that rejects with the provided error.\n       */\n      async throw(err) {\n        await cleanup(true);\n        throw err;\n      }\n    };\n  };\n  return stream;\n}\n\n// src/util/consume-stream.ts\nasync function consumeStream({\n  stream,\n  onError\n}) {\n  const reader = stream.getReader();\n  try {\n    while (true) {\n      const { done } = await reader.read();\n      if (done)\n        break;\n    }\n  } catch (error) {\n    onError == null ? void 0 : onError(error);\n  } finally {\n    reader.releaseLock();\n  }\n}\n\n// src/util/create-resolvable-promise.ts\nfunction createResolvablePromise() {\n  let resolve3;\n  let reject;\n  const promise = new Promise((res, rej) => {\n    resolve3 = res;\n    reject = rej;\n  });\n  return {\n    promise,\n    resolve: resolve3,\n    reject\n  };\n}\n\n// src/util/create-stitchable-stream.ts\nfunction createStitchableStream() {\n  let innerStreamReaders = [];\n  let controller = null;\n  let isClosed = false;\n  let waitForNewStream = createResolvablePromise();\n  const terminate = () => {\n    isClosed = true;\n    waitForNewStream.resolve();\n    innerStreamReaders.forEach((reader) => reader.cancel());\n    innerStreamReaders = [];\n    controller == null ? void 0 : controller.close();\n  };\n  const processPull = async () => {\n    if (isClosed && innerStreamReaders.length === 0) {\n      controller == null ? void 0 : controller.close();\n      return;\n    }\n    if (innerStreamReaders.length === 0) {\n      waitForNewStream = createResolvablePromise();\n      await waitForNewStream.promise;\n      return await processPull();\n    }\n    try {\n      const { value, done } = await innerStreamReaders[0].read();\n      if (done) {\n        innerStreamReaders.shift();\n        if (innerStreamReaders.length === 0 && isClosed) {\n          controller == null ? void 0 : controller.close();\n        } else {\n          await processPull();\n        }\n      } else {\n        controller == null ? void 0 : controller.enqueue(value);\n      }\n    } catch (error) {\n      controller == null ? void 0 : controller.error(error);\n      innerStreamReaders.shift();\n      terminate();\n    }\n  };\n  return {\n    stream: new ReadableStream({\n      start(controllerParam) {\n        controller = controllerParam;\n      },\n      pull: processPull,\n      async cancel() {\n        for (const reader of innerStreamReaders) {\n          await reader.cancel();\n        }\n        innerStreamReaders = [];\n        isClosed = true;\n      }\n    }),\n    addStream: (innerStream) => {\n      if (isClosed) {\n        throw new Error(\"Cannot add inner stream: outer stream is closed\");\n      }\n      innerStreamReaders.push(innerStream.getReader());\n      waitForNewStream.resolve();\n    },\n    /**\n     * Gracefully close the outer stream. This will let the inner streams\n     * finish processing and then close the outer stream.\n     */\n    close: () => {\n      isClosed = true;\n      waitForNewStream.resolve();\n      if (innerStreamReaders.length === 0) {\n        controller == null ? void 0 : controller.close();\n      }\n    },\n    /**\n     * Immediately close the outer stream. This will cancel all inner streams\n     * and close the outer stream.\n     */\n    terminate\n  };\n}\n\n// src/generate-text/execute-tools-from-stream.ts\nfunction executeToolsFromStream({\n  stream,\n  tools,\n  callId,\n  messages,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  toolsContext,\n  toolApproval,\n  runtimeContext,\n  toolApprovalSecret,\n  generateId: generateId2,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  executeToolInTelemetryContext,\n  runInTracingChannelSpan\n}) {\n  const toolCallsToExecute = [];\n  return stream.pipeThrough(\n    new TransformStream({\n      async transform(chunk, controller) {\n        controller.enqueue(chunk);\n        const chunkType = chunk.type;\n        switch (chunkType) {\n          case \"tool-call\": {\n            if (chunk.invalid) {\n              return;\n            }\n            const tool2 = tools == null ? void 0 : tools[chunk.toolName];\n            if (tool2 == null) {\n              return;\n            }\n            const toolApprovalStatus = await resolveToolApproval({\n              tools,\n              toolCall: chunk,\n              toolApproval,\n              messages,\n              toolsContext,\n              runtimeContext\n            });\n            if (toolApprovalStatus.type === \"not-applicable\") {\n              if (tool2.execute != null && chunk.providerExecuted !== true) {\n                toolCallsToExecute.push(chunk);\n              }\n              return;\n            }\n            const approvalId = generateId2();\n            const signature = await maybeSignApproval({\n              secret: toolApprovalSecret,\n              approvalId,\n              toolCallId: chunk.toolCallId,\n              toolName: chunk.toolName,\n              input: chunk.input\n            });\n            switch (toolApprovalStatus.type) {\n              case \"user-approval\": {\n                controller.enqueue({\n                  type: \"tool-approval-request\",\n                  approvalId,\n                  toolCall: chunk,\n                  ...signature != null ? { signature } : {}\n                });\n                return;\n              }\n              case \"denied\": {\n                controller.enqueue({\n                  type: \"tool-approval-request\",\n                  approvalId,\n                  toolCall: chunk,\n                  isAutomatic: true,\n                  ...signature != null ? { signature } : {}\n                });\n                controller.enqueue({\n                  type: \"tool-approval-response\",\n                  approvalId,\n                  approved: false,\n                  toolCall: chunk,\n                  reason: toolApprovalStatus.reason,\n                  providerExecuted: chunk.providerExecuted\n                });\n                return;\n              }\n              case \"approved\": {\n                controller.enqueue({\n                  type: \"tool-approval-request\",\n                  approvalId,\n                  toolCall: chunk,\n                  isAutomatic: true,\n                  ...signature != null ? { signature } : {}\n                });\n                controller.enqueue({\n                  type: \"tool-approval-response\",\n                  approvalId,\n                  approved: true,\n                  toolCall: chunk,\n                  reason: toolApprovalStatus.reason,\n                  providerExecuted: chunk.providerExecuted\n                });\n                break;\n              }\n            }\n            if (tool2.execute != null && chunk.providerExecuted !== true) {\n              toolCallsToExecute.push(chunk);\n            }\n            return;\n          }\n          case \"model-call-end\": {\n            await Promise.all(\n              toolCallsToExecute.map(async (toolCall) => {\n                try {\n                  const result = await executeToolCall({\n                    toolCall,\n                    tools,\n                    callId,\n                    messages,\n                    abortSignal,\n                    timeout,\n                    experimental_sandbox: sandbox,\n                    toolsContext,\n                    onToolExecutionStart,\n                    onToolExecutionEnd,\n                    executeToolInTelemetryContext,\n                    runInTracingChannelSpan,\n                    onPreliminaryToolResult: (result2) => {\n                      controller.enqueue(result2);\n                    }\n                  });\n                  if (result != null) {\n                    controller.enqueue({\n                      type: \"tool-execution-end\",\n                      toolCallId: result.output.toolCallId,\n                      toolExecutionMs: result.toolExecutionMs\n                    });\n                    controller.enqueue(result.output);\n                  }\n                } catch (error) {\n                  controller.enqueue({\n                    type: \"error\",\n                    error\n                  });\n                }\n              })\n            );\n            return;\n          }\n        }\n      }\n    })\n  );\n}\n\n// src/generate-text/invoke-tool-callbacks-from-stream.ts\nfunction invokeToolCallbacksFromStream({\n  stream,\n  tools,\n  stepInputMessages,\n  abortSignal,\n  runtimeContext\n}) {\n  if (tools == null)\n    return stream;\n  const ongoingToolCallToolNames = {};\n  return stream.pipeThrough(\n    new TransformStream({\n      async transform(chunk, controller) {\n        controller.enqueue(chunk);\n        switch (chunk.type) {\n          case \"tool-input-start\": {\n            ongoingToolCallToolNames[chunk.id] = chunk.toolName;\n            const tool2 = tools == null ? void 0 : tools[chunk.toolName];\n            if ((tool2 == null ? void 0 : tool2.onInputStart) != null) {\n              await tool2.onInputStart({\n                toolCallId: chunk.id,\n                messages: stepInputMessages,\n                abortSignal,\n                context: runtimeContext\n              });\n            }\n            break;\n          }\n          case \"tool-input-delta\": {\n            const toolName = ongoingToolCallToolNames[chunk.id];\n            const tool2 = tools == null ? void 0 : tools[toolName];\n            if ((tool2 == null ? void 0 : tool2.onInputDelta) != null) {\n              await tool2.onInputDelta({\n                inputTextDelta: chunk.delta,\n                toolCallId: chunk.id,\n                messages: stepInputMessages,\n                abortSignal,\n                context: runtimeContext\n              });\n            }\n            break;\n          }\n          case \"tool-call\": {\n            const toolName = ongoingToolCallToolNames[chunk.toolCallId];\n            const tool2 = tools == null ? void 0 : tools[toolName];\n            delete ongoingToolCallToolNames[chunk.toolCallId];\n            if ((tool2 == null ? void 0 : tool2.onInputAvailable) != null) {\n              await tool2.onInputAvailable({\n                input: chunk.input,\n                toolCallId: chunk.toolCallId,\n                messages: stepInputMessages,\n                abortSignal,\n                context: runtimeContext\n              });\n            }\n          }\n        }\n      }\n    })\n  );\n}\n\n// src/generate-text/stream-language-model-call.ts\nimport {\n  getErrorMessage as getErrorMessage6\n} from \"@ai-sdk/provider\";\nimport {\n  createIdGenerator as createIdGenerator2\n} from \"@ai-sdk/provider-utils\";\nvar originalGenerateId2 = createIdGenerator2({\n  prefix: \"aitxt\",\n  size: 24\n});\nvar originalGenerateCallId2 = createIdGenerator2({\n  prefix: \"call\",\n  size: 24\n});\nasync function streamLanguageModelCall({\n  model,\n  tools,\n  toolOrder,\n  output,\n  toolChoice,\n  prompt,\n  system,\n  instructions,\n  messages,\n  allowSystemInMessages,\n  download: download2,\n  abortSignal,\n  headers,\n  includeRawChunks,\n  providerOptions,\n  repairToolCall,\n  refineToolInput,\n  executeLanguageModelCallInTelemetryContext = async ({ execute }) => await execute(),\n  callId,\n  toolsContext,\n  experimental_sandbox: sandbox,\n  _internal: {\n    generateId: generateId2 = originalGenerateId2,\n    generateCallId = originalGenerateCallId2,\n    now: now2 = now\n  } = {},\n  onStart,\n  onLanguageModelCallStart,\n  onLanguageModelCallEnd,\n  ...callSettings\n}) {\n  const resolvedModel = resolveLanguageModel(model);\n  const effectiveCallId = callId != null ? callId : generateCallId();\n  const standardizedPrompt = await standardizePrompt({\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages\n  });\n  const promptMessages = await convertToLanguageModelPrompt({\n    prompt: {\n      instructions: standardizedPrompt.instructions,\n      messages: standardizedPrompt.messages\n    },\n    supportedUrls: await resolvedModel.supportedUrls,\n    download: download2,\n    provider: resolvedModel.provider.split(\".\")[0]\n  });\n  const stepTools = await prepareTools({\n    tools,\n    toolOrder,\n    toolsContext,\n    experimental_sandbox: sandbox\n  });\n  const stepToolChoice = prepareToolChoice({\n    toolChoice\n  });\n  await notify({\n    event: { promptMessages },\n    callbacks: onStart\n  });\n  const languageModelCallContext = {\n    provider: resolvedModel.provider,\n    modelId: resolvedModel.modelId,\n    instructions: standardizedPrompt.instructions,\n    messages: standardizedPrompt.messages,\n    tools: stepTools,\n    ...callSettings\n  };\n  const languageModelCallStartEvent = {\n    callId: effectiveCallId,\n    ...languageModelCallContext\n  };\n  await notify({\n    event: languageModelCallStartEvent,\n    callbacks: onLanguageModelCallStart\n  });\n  const callStartTimestampMs = now2();\n  const {\n    stream: languageModelStream,\n    response,\n    request\n  } = await executeLanguageModelCallInTelemetryContext({\n    ...languageModelCallStartEvent,\n    execute: async () => await resolvedModel.doStream({\n      ...callSettings,\n      tools: stepTools,\n      toolChoice: stepToolChoice,\n      responseFormat: await (output == null ? void 0 : output.responseFormat),\n      prompt: promptMessages,\n      providerOptions,\n      abortSignal,\n      headers,\n      includeRawChunks\n    })\n  });\n  const standardizedStream = languageModelStream.pipeThrough(\n    createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({\n      tools,\n      instructions: standardizedPrompt.instructions,\n      messages: standardizedPrompt.messages,\n      repairToolCall,\n      refineToolInput,\n      callId: effectiveCallId,\n      provider: resolvedModel.provider,\n      modelId: resolvedModel.modelId,\n      generateId: generateId2,\n      now: now2,\n      callStartTimestampMs,\n      onLanguageModelCallEnd\n    })\n  );\n  return {\n    stream: createAsyncIterableStream(standardizedStream),\n    response,\n    request\n  };\n}\nfunction createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({\n  tools,\n  instructions,\n  messages,\n  repairToolCall,\n  refineToolInput,\n  callId,\n  provider,\n  modelId,\n  generateId: generateId2,\n  now: now2,\n  callStartTimestampMs,\n  onLanguageModelCallEnd\n}) {\n  const toolCallsByToolCallId = /* @__PURE__ */ new Map();\n  const modelCallContent = [];\n  const textPartIndexes = /* @__PURE__ */ new Map();\n  const reasoningPartIndexes = /* @__PURE__ */ new Map();\n  let responseId = generateId2();\n  let timeToFirstOutputMs;\n  let previousOutputChunkTimestampMs;\n  const timeBetweenOutputChunksMs = [];\n  return new TransformStream({\n    async transform(chunk, controller) {\n      var _a22, _b;\n      if (isOutputChunk(chunk)) {\n        const outputChunkTimestampMs = now2();\n        if (timeToFirstOutputMs == null) {\n          timeToFirstOutputMs = outputChunkTimestampMs - callStartTimestampMs;\n        } else if (previousOutputChunkTimestampMs != null) {\n          timeBetweenOutputChunksMs.push(\n            outputChunkTimestampMs - previousOutputChunkTimestampMs\n          );\n        }\n        previousOutputChunkTimestampMs = outputChunkTimestampMs;\n      }\n      switch (chunk.type) {\n        case \"text-start\":\n          upsertTextContentPart({\n            content: modelCallContent,\n            partIndexes: textPartIndexes,\n            id: chunk.id,\n            type: \"text\",\n            providerMetadata: chunk.providerMetadata\n          });\n          controller.enqueue(chunk);\n          break;\n        case \"text-delta\":\n          upsertTextContentPart({\n            content: modelCallContent,\n            partIndexes: textPartIndexes,\n            id: chunk.id,\n            type: \"text\",\n            textDelta: chunk.delta,\n            providerMetadata: chunk.providerMetadata\n          });\n          controller.enqueue({\n            type: \"text-delta\",\n            id: chunk.id,\n            text: chunk.delta,\n            providerMetadata: chunk.providerMetadata\n          });\n          break;\n        case \"text-end\":\n          upsertTextContentPart({\n            content: modelCallContent,\n            partIndexes: textPartIndexes,\n            id: chunk.id,\n            type: \"text\",\n            providerMetadata: chunk.providerMetadata\n          });\n          textPartIndexes.delete(chunk.id);\n          controller.enqueue(chunk);\n          break;\n        case \"reasoning-start\":\n          upsertTextContentPart({\n            content: modelCallContent,\n            partIndexes: reasoningPartIndexes,\n            id: chunk.id,\n            type: \"reasoning\",\n            providerMetadata: chunk.providerMetadata\n          });\n          controller.enqueue(chunk);\n          break;\n        case \"reasoning-delta\":\n          upsertTextContentPart({\n            content: modelCallContent,\n            partIndexes: reasoningPartIndexes,\n            id: chunk.id,\n            type: \"reasoning\",\n            textDelta: chunk.delta,\n            providerMetadata: chunk.providerMetadata\n          });\n          controller.enqueue({\n            type: \"reasoning-delta\",\n            id: chunk.id,\n            text: chunk.delta,\n            providerMetadata: chunk.providerMetadata\n          });\n          break;\n        case \"reasoning-end\":\n          upsertTextContentPart({\n            content: modelCallContent,\n            partIndexes: reasoningPartIndexes,\n            id: chunk.id,\n            type: \"reasoning\",\n            providerMetadata: chunk.providerMetadata\n          });\n          reasoningPartIndexes.delete(chunk.id);\n          controller.enqueue(chunk);\n          break;\n        case \"file\":\n        case \"reasoning-file\": {\n          const file = new DefaultGeneratedFileWithType({\n            data: chunk.data.type === \"data\" ? chunk.data.data : chunk.data.url.toString(),\n            mediaType: chunk.mediaType\n          });\n          modelCallContent.push({\n            type: chunk.type,\n            file,\n            ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n          });\n          controller.enqueue({\n            type: chunk.type,\n            file,\n            providerMetadata: chunk.providerMetadata\n          });\n          break;\n        }\n        case \"finish\": {\n          const usage = asLanguageModelUsage(chunk.usage);\n          const responseTimeMs = now2() - callStartTimestampMs;\n          const performance = {\n            responseTimeMs,\n            effectiveOutputTokensPerSecond: calculateTokensPerSecond({\n              tokens: usage.outputTokens,\n              durationMs: responseTimeMs\n            }),\n            outputTokensPerSecond: timeToFirstOutputMs == null ? void 0 : calculateTokensPerSecond({\n              tokens: usage.outputTokens,\n              durationMs: responseTimeMs - timeToFirstOutputMs\n            }),\n            inputTokensPerSecond: timeToFirstOutputMs == null ? void 0 : calculateTokensPerSecond({\n              tokens: usage.inputTokens,\n              durationMs: timeToFirstOutputMs\n            }),\n            effectiveTotalTokensPerSecond: calculateTokensPerSecond({\n              tokens: sumTokenCounts(usage.inputTokens, usage.outputTokens),\n              durationMs: responseTimeMs\n            }),\n            timeToFirstOutputMs,\n            timeBetweenOutputChunksMs: timeBetweenOutputChunksMs.length > 0 ? calculateOutputChunkTimingStats(timeBetweenOutputChunksMs) : void 0\n          };\n          await notify({\n            event: {\n              callId,\n              provider,\n              modelId,\n              finishReason: chunk.finishReason.unified,\n              usage,\n              content: modelCallContent,\n              responseId,\n              performance\n            },\n            callbacks: onLanguageModelCallEnd\n          });\n          controller.enqueue({\n            type: \"model-call-end\",\n            finishReason: chunk.finishReason.unified,\n            rawFinishReason: chunk.finishReason.raw,\n            usage,\n            providerMetadata: chunk.providerMetadata,\n            performance\n          });\n          break;\n        }\n        case \"tool-call\": {\n          try {\n            const toolCall = await parseToolCall({\n              toolCall: chunk,\n              tools,\n              repairToolCall,\n              refineToolInput,\n              instructions,\n              messages\n            });\n            toolCallsByToolCallId.set(toolCall.toolCallId, toolCall);\n            controller.enqueue(toolCall);\n            modelCallContent.push(toolCall);\n            if (toolCall.invalid) {\n              controller.enqueue({\n                type: \"tool-error\",\n                toolCallId: toolCall.toolCallId,\n                toolName: toolCall.toolName,\n                input: toolCall.input,\n                error: getErrorMessage6(toolCall.error),\n                dynamic: true,\n                title: toolCall.title,\n                ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n              });\n              break;\n            }\n          } catch (error) {\n            controller.enqueue({ type: \"error\", error });\n          }\n          break;\n        }\n        case \"tool-approval-request\": {\n          const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n          if (toolCall == null) {\n            controller.enqueue({\n              type: \"error\",\n              error: new ToolCallNotFoundForApprovalError({\n                toolCallId: chunk.toolCallId,\n                approvalId: chunk.approvalId\n              })\n            });\n            break;\n          }\n          const toolApprovalRequest = {\n            type: \"tool-approval-request\",\n            approvalId: chunk.approvalId,\n            toolCall\n          };\n          controller.enqueue(toolApprovalRequest);\n          modelCallContent.push(toolApprovalRequest);\n          break;\n        }\n        case \"tool-result\": {\n          const toolName = chunk.toolName;\n          const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n          const toolResultPart = chunk.isError ? {\n            type: \"tool-error\",\n            toolCallId: chunk.toolCallId,\n            toolName,\n            input: toolCall == null ? void 0 : toolCall.input,\n            providerExecuted: true,\n            error: chunk.result,\n            dynamic: chunk.dynamic,\n            ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},\n            ...(toolCall == null ? void 0 : toolCall.toolMetadata) != null ? { toolMetadata: toolCall.toolMetadata } : {}\n          } : {\n            type: \"tool-result\",\n            toolCallId: chunk.toolCallId,\n            toolName,\n            input: toolCall == null ? void 0 : toolCall.input,\n            output: chunk.result,\n            providerExecuted: true,\n            dynamic: chunk.dynamic,\n            ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},\n            ...(toolCall == null ? void 0 : toolCall.toolMetadata) != null ? { toolMetadata: toolCall.toolMetadata } : {}\n          };\n          controller.enqueue(toolResultPart);\n          modelCallContent.push(toolResultPart);\n          break;\n        }\n        case \"tool-input-start\": {\n          const tool2 = tools == null ? void 0 : tools[chunk.toolName];\n          controller.enqueue({\n            ...chunk,\n            dynamic: (_a22 = chunk.dynamic) != null ? _a22 : (tool2 == null ? void 0 : tool2.type) === \"dynamic\",\n            title: tool2 == null ? void 0 : tool2.title,\n            ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}\n          });\n          break;\n        }\n        case \"stream-start\": {\n          controller.enqueue({\n            type: \"model-call-start\",\n            warnings: chunk.warnings\n          });\n          break;\n        }\n        case \"response-metadata\": {\n          responseId = (_b = chunk.id) != null ? _b : responseId;\n          controller.enqueue({\n            type: \"model-call-response-metadata\",\n            id: chunk.id,\n            timestamp: chunk.timestamp,\n            modelId: chunk.modelId\n          });\n          break;\n        }\n        default:\n          if (chunk.type === \"custom\" || chunk.type === \"source\") {\n            modelCallContent.push(chunk);\n          }\n          controller.enqueue(chunk);\n          break;\n      }\n    }\n  });\n}\nfunction isOutputChunk(chunk) {\n  return chunk.type === \"text-delta\" && chunk.delta.length > 0 || chunk.type === \"reasoning-delta\" && chunk.delta.length > 0 || chunk.type === \"tool-input-delta\" && chunk.delta.length > 0 || chunk.type === \"file\" || chunk.type === \"reasoning-file\" || chunk.type === \"tool-call\";\n}\nfunction calculateOutputChunkTimingStats(timingsMs) {\n  const sortedTimingsMs = [...timingsMs].sort((a, b) => a - b);\n  const sum = timingsMs.reduce((sum2, timingMs) => sum2 + timingMs, 0);\n  return {\n    min: sortedTimingsMs[0],\n    p10: calculateNearestRankPercentile(sortedTimingsMs, 0.1),\n    median: calculateNearestRankPercentile(sortedTimingsMs, 0.5),\n    avg: sum / timingsMs.length,\n    p90: calculateNearestRankPercentile(sortedTimingsMs, 0.9),\n    max: sortedTimingsMs[sortedTimingsMs.length - 1]\n  };\n}\nfunction calculateNearestRankPercentile(sortedValues, percentile) {\n  return sortedValues[Math.ceil(percentile * sortedValues.length) - 1];\n}\nfunction upsertTextContentPart({\n  content,\n  partIndexes,\n  id,\n  type,\n  textDelta,\n  providerMetadata\n}) {\n  let partIndex = partIndexes.get(id);\n  if (partIndex == null) {\n    partIndex = content.push({\n      type,\n      text: \"\",\n      ...providerMetadata != null ? { providerMetadata } : {}\n    }) - 1;\n    partIndexes.set(id, partIndex);\n  }\n  const part = content[partIndex];\n  if (textDelta != null) {\n    part.text += textDelta;\n  }\n  if (providerMetadata != null) {\n    part.providerMetadata = providerMetadata;\n  }\n}\n\n// src/generate-text/stream-text.ts\nvar originalGenerateId3 = createIdGenerator3({\n  prefix: \"aitxt\",\n  size: 24\n});\nvar originalGenerateCallId3 = createIdGenerator3({\n  prefix: \"call\",\n  size: 24\n});\nvar isOutputChunkType = {\n  file: true,\n  custom: true,\n  source: true,\n  \"text-start\": true,\n  \"text-end\": true,\n  \"text-delta\": true,\n  \"reasoning-start\": true,\n  \"reasoning-end\": true,\n  \"reasoning-delta\": true,\n  \"reasoning-file\": true,\n  \"tool-input-start\": true,\n  \"tool-input-end\": true,\n  \"tool-input-delta\": true,\n  \"tool-approval-request\": true,\n  \"tool-approval-response\": true,\n  \"tool-call\": true,\n  \"tool-result\": true,\n  \"tool-error\": true,\n  \"tool-execution-end\": false,\n  \"model-call-start\": false,\n  \"model-call-response-metadata\": false,\n  \"model-call-end\": false,\n  error: false,\n  raw: false\n};\nfunction streamText({\n  model,\n  tools,\n  toolChoice,\n  instructions,\n  system,\n  prompt,\n  messages,\n  allowSystemInMessages,\n  maxRetries,\n  abortSignal,\n  timeout,\n  headers,\n  stopWhen = isStepCount(1),\n  experimental_sandbox: sandbox,\n  output,\n  toolApproval,\n  experimental_toolApprovalSecret,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  prepareStep,\n  providerOptions,\n  activeTools,\n  toolOrder,\n  experimental_repairToolCall: repairToolCall,\n  experimental_refineToolInput: refineToolInput,\n  experimental_transform: transform,\n  experimental_download: download2,\n  includeRawChunks,\n  onChunk,\n  onError = ({ error }) => {\n    console.error(error);\n  },\n  onFinish,\n  onEnd = onFinish,\n  onAbort,\n  onStepEnd,\n  onStepFinish,\n  onStart,\n  experimental_onStart,\n  onStepStart,\n  experimental_onStepStart,\n  onLanguageModelCallStart,\n  experimental_onLanguageModelCallStart,\n  onLanguageModelCallEnd,\n  experimental_onLanguageModelCallEnd,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  experimental_onToolCallStart,\n  experimental_onToolCallFinish,\n  runtimeContext = {},\n  toolsContext = {},\n  experimental_include,\n  include = experimental_include,\n  _internal: {\n    now: now2 = now,\n    generateId: generateId2 = originalGenerateId3,\n    generateCallId = originalGenerateCallId3\n  } = {},\n  ...settings\n}) {\n  var _a22, _b, _c, _d;\n  const totalTimeoutMs = getTotalTimeoutMs(timeout);\n  const stepTimeoutMs = getStepTimeoutMs(timeout);\n  const chunkTimeoutMs = getChunkTimeoutMs(timeout);\n  const stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n  const chunkAbortController = chunkTimeoutMs != null ? new AbortController() : void 0;\n  const resolvedOnStart = onStart != null ? onStart : experimental_onStart;\n  const resolvedOnStepStart = onStepStart != null ? onStepStart : experimental_onStepStart;\n  const resolvedOnLanguageModelCallStart = onLanguageModelCallStart != null ? onLanguageModelCallStart : experimental_onLanguageModelCallStart;\n  const resolvedOnLanguageModelCallEnd = onLanguageModelCallEnd != null ? onLanguageModelCallEnd : experimental_onLanguageModelCallEnd;\n  const resolvedOnToolExecutionStart = onToolExecutionStart != null ? onToolExecutionStart : experimental_onToolCallStart;\n  const resolvedOnToolExecutionEnd = onToolExecutionEnd != null ? onToolExecutionEnd : experimental_onToolCallFinish;\n  const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish;\n  return new DefaultStreamTextResult({\n    model: resolveLanguageModel(model),\n    telemetry,\n    headers,\n    settings,\n    maxRetries,\n    abortSignal: mergeAbortSignals(\n      abortSignal,\n      totalTimeoutMs,\n      stepAbortController == null ? void 0 : stepAbortController.signal,\n      chunkAbortController == null ? void 0 : chunkAbortController.signal\n    ),\n    stepTimeoutMs,\n    stepAbortController,\n    chunkTimeoutMs,\n    chunkAbortController,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    experimental_sandbox: sandbox,\n    tools,\n    toolsContext,\n    runtimeContext,\n    toolChoice,\n    transforms: asArray6(transform),\n    activeTools,\n    toolOrder,\n    repairToolCall,\n    refineToolInput,\n    stopConditions: asArray6(stopWhen),\n    output,\n    toolApproval,\n    experimental_toolApprovalSecret,\n    providerOptions,\n    prepareStep,\n    timeout,\n    onChunk,\n    onError,\n    onEnd,\n    onAbort,\n    onStepFinish: resolvedOnStepEnd,\n    onStart: resolvedOnStart,\n    onStepStart: resolvedOnStepStart,\n    onLanguageModelCallStart: resolvedOnLanguageModelCallStart,\n    onLanguageModelCallEnd: resolvedOnLanguageModelCallEnd,\n    onToolExecutionStart: resolvedOnToolExecutionStart,\n    onToolExecutionEnd: resolvedOnToolExecutionEnd,\n    now: now2,\n    generateId: generateId2,\n    generateCallId,\n    download: download2,\n    // assign default values to include:\n    include: {\n      requestBody: (_a22 = include == null ? void 0 : include.requestBody) != null ? _a22 : false,\n      requestMessages: (_b = include == null ? void 0 : include.requestMessages) != null ? _b : false,\n      rawChunks: (_d = (_c = include == null ? void 0 : include.rawChunks) != null ? _c : includeRawChunks) != null ? _d : false\n    }\n  });\n}\nasync function markPromiseAsHandled(promise) {\n  try {\n    await promise;\n  } catch (e) {\n  }\n}\nfunction createOutputTransformStream(output) {\n  let firstTextChunkId = void 0;\n  let text2 = \"\";\n  let textChunk = \"\";\n  let textProviderMetadata = void 0;\n  let lastPublishedValue = \"\";\n  function publishTextChunk({\n    controller,\n    partialOutput = void 0\n  }) {\n    controller.enqueue({\n      part: {\n        type: \"text-delta\",\n        id: firstTextChunkId,\n        text: textChunk,\n        providerMetadata: textProviderMetadata\n      },\n      partialOutput\n    });\n    textChunk = \"\";\n  }\n  return new TransformStream({\n    async transform(chunk, controller) {\n      var _a22;\n      if (chunk.type === \"finish-step\" && textChunk.length > 0) {\n        publishTextChunk({ controller });\n      }\n      if (chunk.type !== \"text-delta\" && chunk.type !== \"text-start\" && chunk.type !== \"text-end\") {\n        controller.enqueue({ part: chunk, partialOutput: void 0 });\n        return;\n      }\n      if (firstTextChunkId == null) {\n        firstTextChunkId = chunk.id;\n      } else if (chunk.id !== firstTextChunkId) {\n        controller.enqueue({ part: chunk, partialOutput: void 0 });\n        return;\n      }\n      if (chunk.type === \"text-start\") {\n        controller.enqueue({ part: chunk, partialOutput: void 0 });\n        return;\n      }\n      if (chunk.type === \"text-end\") {\n        if (textChunk.length > 0) {\n          publishTextChunk({ controller });\n        }\n        controller.enqueue({ part: chunk, partialOutput: void 0 });\n        return;\n      }\n      text2 += chunk.text;\n      textChunk += chunk.text;\n      textProviderMetadata = (_a22 = chunk.providerMetadata) != null ? _a22 : textProviderMetadata;\n      const result = await output.parsePartialOutput({ text: text2 });\n      if (result !== void 0) {\n        const currentValue = typeof result.partial === \"string\" ? result.partial : JSON.stringify(result.partial);\n        if (currentValue !== lastPublishedValue) {\n          publishTextChunk({ controller, partialOutput: result.partial });\n          lastPublishedValue = currentValue;\n        }\n      }\n    }\n  });\n}\nvar DefaultStreamTextResult = class {\n  constructor({\n    model,\n    telemetry,\n    headers,\n    settings,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    stepTimeoutMs,\n    stepAbortController,\n    chunkTimeoutMs,\n    chunkAbortController,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    experimental_sandbox: sandbox,\n    tools,\n    toolChoice,\n    transforms,\n    activeTools,\n    toolOrder,\n    repairToolCall,\n    refineToolInput,\n    stopConditions,\n    output,\n    toolApproval,\n    experimental_toolApprovalSecret,\n    providerOptions,\n    prepareStep,\n    now: now2,\n    generateId: generateId2,\n    generateCallId,\n    timeout,\n    onChunk,\n    onError,\n    onEnd,\n    onAbort,\n    onStepFinish,\n    onStart,\n    onStepStart,\n    onLanguageModelCallStart,\n    onLanguageModelCallEnd,\n    onToolExecutionStart,\n    onToolExecutionEnd,\n    runtimeContext,\n    toolsContext,\n    download: download2,\n    include\n  }) {\n    this._totalUsage = new DelayedPromise();\n    this._finishReason = new DelayedPromise();\n    this._rawFinishReason = new DelayedPromise();\n    this._steps = new DelayedPromise();\n    this._initialResponseMessages = new DelayedPromise();\n    this.outputSpecification = output;\n    this.tools = tools;\n    const telemetryDispatcher = createRestrictedTelemetryDispatcher({\n      telemetry,\n      includeRuntimeContext: telemetry == null ? void 0 : telemetry.includeRuntimeContext,\n      includeToolsContext: telemetry == null ? void 0 : telemetry.includeToolsContext\n    });\n    let stepFinish;\n    let recordedContent = [];\n    let recordedFinishReason = void 0;\n    let recordedRawFinishReason = void 0;\n    let recordedTotalUsage = void 0;\n    let recordedRequest = {};\n    let recordedRequestMessages = [];\n    let recordedWarnings = [];\n    const recordedSteps = [];\n    const initialResponseMessages = [];\n    let stepMessagesForNextStep;\n    let currentStepMessages = [];\n    const pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n    let activeTextContent = createIdMap();\n    let activeReasoningContent = createIdMap();\n    let recordedNoOutputError;\n    const eventProcessor = new TransformStream({\n      async transform(chunk, controller) {\n        var _a22, _b, _c, _d;\n        controller.enqueue(chunk);\n        const { part } = chunk;\n        await (onChunk == null ? void 0 : onChunk({ chunk: part }));\n        if (part.type === \"error\") {\n          const error = wrapGatewayError(part.error);\n          if (NoOutputGeneratedError.isInstance(error)) {\n            recordedNoOutputError = error;\n          }\n          await onError({ error });\n        }\n        if (part.type === \"custom\" || part.type === \"source\" || part.type === \"tool-call\" || part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\" || part.type === \"tool-error\") {\n          recordedContent.push(part);\n        }\n        if (part.type === \"text-start\") {\n          activeTextContent[part.id] = {\n            type: \"text\",\n            text: \"\",\n            providerMetadata: part.providerMetadata\n          };\n          recordedContent.push(activeTextContent[part.id]);\n        }\n        if (part.type === \"text-delta\") {\n          const activeText = activeTextContent[part.id];\n          if (activeText == null) {\n            controller.enqueue({\n              part: {\n                type: \"error\",\n                error: `text part ${part.id} not found`\n              },\n              partialOutput: void 0\n            });\n            return;\n          }\n          activeText.text += part.text;\n          activeText.providerMetadata = (_a22 = part.providerMetadata) != null ? _a22 : activeText.providerMetadata;\n        }\n        if (part.type === \"text-end\") {\n          const activeText = activeTextContent[part.id];\n          if (activeText == null) {\n            controller.enqueue({\n              part: {\n                type: \"error\",\n                error: `text part ${part.id} not found`\n              },\n              partialOutput: void 0\n            });\n            return;\n          }\n          activeText.providerMetadata = (_b = part.providerMetadata) != null ? _b : activeText.providerMetadata;\n          delete activeTextContent[part.id];\n        }\n        if (part.type === \"reasoning-start\") {\n          activeReasoningContent[part.id] = {\n            type: \"reasoning\",\n            text: \"\",\n            providerMetadata: part.providerMetadata\n          };\n          recordedContent.push(activeReasoningContent[part.id]);\n        }\n        if (part.type === \"reasoning-delta\") {\n          const activeReasoning = activeReasoningContent[part.id];\n          if (activeReasoning == null) {\n            controller.enqueue({\n              part: {\n                type: \"error\",\n                error: `reasoning part ${part.id} not found`\n              },\n              partialOutput: void 0\n            });\n            return;\n          }\n          activeReasoning.text += part.text;\n          activeReasoning.providerMetadata = (_c = part.providerMetadata) != null ? _c : activeReasoning.providerMetadata;\n        }\n        if (part.type === \"reasoning-end\") {\n          const activeReasoning = activeReasoningContent[part.id];\n          if (activeReasoning == null) {\n            controller.enqueue({\n              part: {\n                type: \"error\",\n                error: `reasoning part ${part.id} not found`\n              },\n              partialOutput: void 0\n            });\n            return;\n          }\n          activeReasoning.providerMetadata = (_d = part.providerMetadata) != null ? _d : activeReasoning.providerMetadata;\n          delete activeReasoningContent[part.id];\n        }\n        if (part.type === \"file\" || part.type === \"reasoning-file\") {\n          recordedContent.push({\n            type: part.type,\n            file: part.file,\n            ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n          });\n        }\n        if (part.type === \"tool-result\" && !part.preliminary) {\n          recordedContent.push(part);\n        }\n        if (part.type === \"start-step\") {\n          recordedContent = [];\n          activeReasoningContent = createIdMap();\n          activeTextContent = createIdMap();\n          recordedRequest = part.request;\n          recordedWarnings = part.warnings;\n        }\n        if (part.type === \"finish-step\") {\n          const stepResponseMessages = await toResponseMessages({\n            content: recordedContent,\n            tools\n          });\n          const currentStepResult = new DefaultStepResult({\n            callId,\n            stepNumber: recordedSteps.length,\n            provider: model.provider,\n            modelId: model.modelId,\n            runtimeContext,\n            toolsContext,\n            content: recordedContent,\n            finishReason: part.finishReason,\n            rawFinishReason: part.rawFinishReason,\n            usage: part.usage,\n            performance: part.performance,\n            warnings: recordedWarnings,\n            request: {\n              ...recordedRequest,\n              messages: include.requestMessages ? cloneModelMessages(recordedRequestMessages) : void 0\n            },\n            response: {\n              ...part.response,\n              messages: cloneModelMessages(stepResponseMessages)\n            },\n            providerMetadata: part.providerMetadata\n          });\n          await notify({\n            event: currentStepResult,\n            callbacks: [onStepFinish, telemetryDispatcher.onStepEnd]\n          });\n          logWarnings({\n            warnings: recordedWarnings,\n            provider: model.provider,\n            model: model.modelId\n          });\n          recordedSteps.push(currentStepResult);\n          stepMessagesForNextStep = [\n            ...currentStepMessages,\n            ...stepResponseMessages\n          ];\n          stepFinish.resolve();\n        }\n        if (part.type === \"finish\") {\n          recordedTotalUsage = part.totalUsage;\n          recordedFinishReason = part.finishReason;\n          recordedRawFinishReason = part.rawFinishReason;\n        }\n      },\n      async flush(controller) {\n        try {\n          if (recordedSteps.length === 0 || recordedNoOutputError != null) {\n            const error = (abortSignal == null ? void 0 : abortSignal.aborted) ? abortSignal.reason : recordedNoOutputError != null ? recordedNoOutputError : new NoOutputGeneratedError({\n              message: \"No output generated. Check the stream for errors.\"\n            });\n            self.rejectResultPromises(error);\n            return;\n          }\n          const finishReason = recordedFinishReason != null ? recordedFinishReason : \"other\";\n          const totalUsage = recordedTotalUsage != null ? recordedTotalUsage : createNullLanguageModelUsage();\n          self._finishReason.resolve(finishReason);\n          self._rawFinishReason.resolve(recordedRawFinishReason);\n          self._totalUsage.resolve(totalUsage);\n          self._steps.resolve(recordedSteps);\n          const finalStep = recordedSteps[recordedSteps.length - 1];\n          const content = recordedSteps.flatMap((step) => step.content);\n          const files = recordedSteps.flatMap((step) => step.files);\n          const sources = recordedSteps.flatMap((step) => step.sources);\n          const toolCalls = recordedSteps.flatMap((step) => step.toolCalls);\n          const staticToolCalls = recordedSteps.flatMap(\n            (step) => step.staticToolCalls\n          );\n          const dynamicToolCalls = recordedSteps.flatMap(\n            (step) => step.dynamicToolCalls\n          );\n          const toolResults = recordedSteps.flatMap((step) => step.toolResults);\n          const staticToolResults = recordedSteps.flatMap(\n            (step) => step.staticToolResults\n          );\n          const dynamicToolResults = recordedSteps.flatMap(\n            (step) => step.dynamicToolResults\n          );\n          const warnings = recordedSteps.flatMap((step) => {\n            var _a22;\n            return (_a22 = step.warnings) != null ? _a22 : [];\n          });\n          await notify({\n            event: {\n              callId,\n              toolsContext: finalStep.toolsContext,\n              stepNumber: finalStep.stepNumber,\n              model: finalStep.model,\n              runtimeContext: finalStep.runtimeContext,\n              finishReason: finalStep.finishReason,\n              rawFinishReason: finalStep.rawFinishReason,\n              usage: totalUsage,\n              totalUsage,\n              content,\n              text: finalStep.text,\n              reasoning: finalStep.reasoning,\n              reasoningText: finalStep.reasoningText,\n              files,\n              sources,\n              toolCalls,\n              staticToolCalls,\n              dynamicToolCalls,\n              toolResults,\n              staticToolResults,\n              dynamicToolResults,\n              responseMessages: [\n                ...initialResponseMessages,\n                ...recordedSteps.flatMap((step) => step.response.messages)\n              ],\n              warnings,\n              request: finalStep.request,\n              response: finalStep.response,\n              providerMetadata: finalStep.providerMetadata,\n              steps: recordedSteps,\n              finalStep\n            },\n            callbacks: [onEnd, telemetryDispatcher.onEnd]\n          });\n        } catch (error) {\n          controller.error(error);\n        }\n      }\n    });\n    const stitchableStream = createStitchableStream();\n    this.addStream = stitchableStream.addStream;\n    this.closeStream = stitchableStream.close;\n    const reader = stitchableStream.stream.getReader();\n    let stream = new ReadableStream({\n      async start(controller) {\n        controller.enqueue({ type: \"start\" });\n      },\n      async pull(controller) {\n        async function abort() {\n          await notify({\n            event: {\n              callId,\n              steps: recordedSteps,\n              ...(abortSignal == null ? void 0 : abortSignal.reason) !== void 0 ? { reason: abortSignal.reason } : {}\n            },\n            callbacks: [onAbort, telemetryDispatcher.onAbort]\n          });\n          controller.enqueue({\n            type: \"abort\",\n            // The `reason` is usually of type DOMException, but it can also be of any type,\n            // so we use getErrorMessage for serialization because it is already designed to accept values of the unknown type.\n            // See: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason\n            ...(abortSignal == null ? void 0 : abortSignal.reason) !== void 0 ? { reason: getErrorMessage7(abortSignal.reason) } : {}\n          });\n          controller.close();\n        }\n        try {\n          const { done, value } = await reader.read();\n          if (done) {\n            controller.close();\n            return;\n          }\n          if (abortSignal == null ? void 0 : abortSignal.aborted) {\n            await abort();\n            return;\n          }\n          controller.enqueue(value);\n        } catch (error) {\n          if (isAbortError2(error) && (abortSignal == null ? void 0 : abortSignal.aborted)) {\n            await abort();\n          } else {\n            controller.error(error);\n          }\n        }\n      },\n      cancel(reason) {\n        return stitchableStream.stream.cancel(reason);\n      }\n    });\n    let isRunning = true;\n    stream = stream.pipeThrough(\n      new TransformStream({\n        async transform(chunk, controller) {\n          if (isRunning) {\n            controller.enqueue(chunk);\n          }\n        }\n      })\n    );\n    for (const transform of transforms) {\n      stream = stream.pipeThrough(\n        transform({\n          tools,\n          stopStream() {\n            stitchableStream.terminate();\n            isRunning = false;\n          }\n        })\n      );\n    }\n    this.baseStream = stream.pipeThrough(createOutputTransformStream(output != null ? output : text())).pipeThrough(eventProcessor);\n    const { maxRetries } = prepareRetries({\n      maxRetries: maxRetriesArg,\n      abortSignal\n    });\n    const callSettings = prepareLanguageModelCallOptions(settings);\n    const self = this;\n    const callId = generateCallId();\n    (async () => {\n      var _a22;\n      const initialPrompt = await standardizePrompt({\n        instructions,\n        system,\n        prompt,\n        messages,\n        allowSystemInMessages\n      });\n      const startEvent = {\n        callId,\n        operationId: \"ai.streamText\",\n        provider: model.provider,\n        modelId: model.modelId,\n        instructions: initialPrompt.instructions,\n        messages: initialPrompt.messages,\n        tools,\n        toolChoice,\n        activeTools,\n        toolOrder,\n        maxOutputTokens: callSettings.maxOutputTokens,\n        temperature: callSettings.temperature,\n        topP: callSettings.topP,\n        topK: callSettings.topK,\n        presencePenalty: callSettings.presencePenalty,\n        frequencyPenalty: callSettings.frequencyPenalty,\n        stopSequences: callSettings.stopSequences,\n        seed: callSettings.seed,\n        reasoning: callSettings.reasoning,\n        maxRetries,\n        timeout,\n        headers,\n        providerOptions,\n        output,\n        runtimeContext,\n        toolsContext\n      };\n      const streamTextTracingChannelContext = (_a22 = telemetryDispatcher.startTracingChannelContext) == null ? void 0 : _a22.call(telemetryDispatcher, {\n        type: \"streamText\",\n        event: startEvent,\n        completion: self._totalUsage.promise.then(() => void 0)\n      });\n      const runInStreamTextTracingChannelContext = (execute) => {\n        var _a23;\n        return (_a23 = streamTextTracingChannelContext == null ? void 0 : streamTextTracingChannelContext.run(execute)) != null ? _a23 : execute();\n      };\n      await notify({\n        event: startEvent,\n        callbacks: [onStart, telemetryDispatcher.onStart]\n      });\n      const initialMessages = initialPrompt.messages;\n      let instructionsForNextStep = initialPrompt.instructions;\n      const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });\n      if (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {\n        const {\n          approvedToolApprovals: localApprovedToolApprovals,\n          deniedToolApprovals: revalidationDeniedToolApprovals\n        } = await validateApprovedToolApprovals({\n          approvedToolApprovals: approvedToolApprovals.filter(\n            (toolApproval2) => !toolApproval2.toolCall.providerExecuted\n          ),\n          tools,\n          toolApproval,\n          messages: initialMessages,\n          toolsContext,\n          runtimeContext,\n          toolApprovalSecret: experimental_toolApprovalSecret\n        });\n        const localDeniedToolApprovals = [\n          ...deniedToolApprovals.filter(\n            (toolApproval2) => !toolApproval2.toolCall.providerExecuted\n          ),\n          ...revalidationDeniedToolApprovals\n        ];\n        const deniedProviderExecutedToolApprovals = deniedToolApprovals.filter(\n          (toolApproval2) => toolApproval2.toolCall.providerExecuted\n        );\n        let toolExecutionStepStreamController;\n        const toolExecutionStepStream = new ReadableStream({\n          start(controller) {\n            toolExecutionStepStreamController = controller;\n          }\n        });\n        self.addStream(toolExecutionStepStream);\n        try {\n          for (const toolApproval2 of [\n            ...localDeniedToolApprovals,\n            ...deniedProviderExecutedToolApprovals\n          ]) {\n            toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue({\n              type: \"tool-output-denied\",\n              toolCallId: toolApproval2.toolCall.toolCallId,\n              toolName: toolApproval2.toolCall.toolName\n            });\n          }\n          const toolOutputs = [];\n          await Promise.all(\n            localApprovedToolApprovals.map(async (toolApproval2) => {\n              const result = await executeToolCall({\n                toolCall: toolApproval2.toolCall,\n                tools,\n                callId,\n                messages: initialMessages,\n                abortSignal,\n                timeout,\n                experimental_sandbox: sandbox,\n                toolsContext,\n                onToolExecutionStart: filterNullable2(\n                  onToolExecutionStart,\n                  telemetryDispatcher.onToolExecutionStart\n                ),\n                onToolExecutionEnd: filterNullable2(\n                  onToolExecutionEnd,\n                  telemetryDispatcher.onToolExecutionEnd\n                ),\n                executeToolInTelemetryContext: telemetryDispatcher.executeTool,\n                runInTracingChannelSpan: telemetryDispatcher.runInTracingChannelSpan,\n                onPreliminaryToolResult: (result2) => {\n                  toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result2);\n                }\n              });\n              if (result != null) {\n                toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result.output);\n                toolOutputs.push(result.output);\n              }\n            })\n          );\n          if (toolOutputs.length > 0 || localDeniedToolApprovals.length > 0) {\n            const localToolContent = [];\n            for (const output2 of toolOutputs) {\n              localToolContent.push({\n                type: \"tool-result\",\n                toolCallId: output2.toolCallId,\n                toolName: output2.toolName,\n                output: await createToolModelOutput({\n                  toolCallId: output2.toolCallId,\n                  input: output2.input,\n                  tool: tools == null ? void 0 : tools[output2.toolName],\n                  output: output2.type === \"tool-result\" ? output2.output : output2.error,\n                  errorMode: output2.type === \"tool-error\" ? \"text\" : \"none\"\n                })\n              });\n            }\n            for (const toolApproval2 of localDeniedToolApprovals) {\n              localToolContent.push({\n                type: \"tool-result\",\n                toolCallId: toolApproval2.toolCall.toolCallId,\n                toolName: toolApproval2.toolCall.toolName,\n                output: {\n                  type: \"execution-denied\",\n                  reason: toolApproval2.approvalResponse.reason\n                }\n              });\n            }\n            initialResponseMessages.push({\n              role: \"tool\",\n              content: localToolContent\n            });\n          }\n        } finally {\n          toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.close();\n        }\n      }\n      self._initialResponseMessages.resolve(initialResponseMessages);\n      async function streamStep({\n        currentStep,\n        usage\n      }) {\n        var _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;\n        const stepTimeoutId = setAbortTimeout({\n          abortController: stepAbortController,\n          label: \"Step\",\n          timeoutMs: stepTimeoutMs\n        });\n        let chunkTimeoutId = void 0;\n        function resetChunkTimeout() {\n          if (chunkTimeoutId != null) {\n            clearTimeout(chunkTimeoutId);\n          }\n          chunkTimeoutId = setAbortTimeout({\n            abortController: chunkAbortController,\n            label: \"Chunk\",\n            timeoutMs: chunkTimeoutMs\n          });\n        }\n        function clearChunkTimeout() {\n          if (chunkTimeoutId != null) {\n            clearTimeout(chunkTimeoutId);\n            chunkTimeoutId = void 0;\n          }\n        }\n        function clearStepTimeout() {\n          if (stepTimeoutId != null) {\n            clearTimeout(stepTimeoutId);\n          }\n        }\n        abortSignal == null ? void 0 : abortSignal.addEventListener(\"abort\", clearStepTimeout);\n        abortSignal == null ? void 0 : abortSignal.addEventListener(\"abort\", clearChunkTimeout);\n        try {\n          stepFinish = new DelayedPromise();\n          const stepTracingChannelContext = (_a23 = telemetryDispatcher.startTracingChannelContext) == null ? void 0 : _a23.call(telemetryDispatcher, {\n            type: \"step\",\n            event: { callId, stepNumber: currentStep },\n            completion: stepFinish.promise\n          });\n          const runInStepTracingChannelContext = (execute) => {\n            var _a24;\n            return (_a24 = stepTracingChannelContext == null ? void 0 : stepTracingChannelContext.run(execute)) != null ? _a24 : execute();\n          };\n          const responseMessagesFromPreviousSteps = recordedSteps.flatMap(\n            (step) => step.response.messages\n          );\n          const accumulatedResponseMessages = [\n            ...initialResponseMessages,\n            ...responseMessagesFromPreviousSteps\n          ];\n          const stepInputMessages = stepMessagesForNextStep != null ? stepMessagesForNextStep : [\n            ...initialMessages,\n            ...initialResponseMessages\n          ];\n          const prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n            model,\n            steps: recordedSteps,\n            stepNumber: recordedSteps.length,\n            instructions: instructionsForNextStep,\n            initialInstructions: initialPrompt.instructions,\n            messages: stepInputMessages,\n            initialMessages,\n            responseMessages: accumulatedResponseMessages,\n            toolsContext,\n            runtimeContext,\n            experimental_sandbox: sandbox\n          }));\n          const stepSandbox = (_b = prepareStepResult == null ? void 0 : prepareStepResult.experimental_sandbox) != null ? _b : sandbox;\n          runtimeContext = (_c = prepareStepResult == null ? void 0 : prepareStepResult.runtimeContext) != null ? _c : runtimeContext;\n          toolsContext = (_d = prepareStepResult == null ? void 0 : prepareStepResult.toolsContext) != null ? _d : toolsContext;\n          const stepModel = resolveLanguageModel(\n            (_e = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _e : model\n          );\n          const stepActiveTools = filterActiveTools({\n            tools,\n            activeTools: (_f = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _f : activeTools\n          });\n          const stepToolOrder = (_g = prepareStepResult == null ? void 0 : prepareStepResult.toolOrder) != null ? _g : toolOrder;\n          const stepTools = await prepareTools({\n            tools: stepActiveTools,\n            toolOrder: stepToolOrder,\n            // active tools context is a subset of the tools context, so we can cast to the unknown type\n            toolsContext,\n            experimental_sandbox: stepSandbox\n          });\n          const stepToolChoice = prepareToolChoice({\n            toolChoice: (_h = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _h : toolChoice\n          });\n          const stepMessages = (_i = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _i : stepInputMessages;\n          currentStepMessages = stepMessages;\n          const stepInstructions = (_k = (_j = prepareStepResult == null ? void 0 : prepareStepResult.instructions) != null ? _j : prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _k : instructionsForNextStep;\n          instructionsForNextStep = stepInstructions;\n          const stepProviderOptions = mergeObjects(\n            providerOptions,\n            prepareStepResult == null ? void 0 : prepareStepResult.providerOptions\n          );\n          const stepStartTimestampMs = now2();\n          const { retry } = prepareRetries({ maxRetries, abortSignal });\n          const {\n            stream: languageModelStream,\n            request,\n            response\n          } = await runInStepTracingChannelContext(\n            () => retry(\n              async () => {\n                var _a24, _b2;\n                return streamLanguageModelCall({\n                  model: (_a24 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a24 : model,\n                  tools: stepActiveTools,\n                  toolOrder: stepToolOrder,\n                  toolChoice: (_b2 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _b2 : toolChoice,\n                  instructions: stepInstructions,\n                  messages: stepMessages,\n                  allowSystemInMessages,\n                  repairToolCall,\n                  refineToolInput,\n                  abortSignal,\n                  headers,\n                  includeRawChunks: include.rawChunks,\n                  providerOptions: stepProviderOptions,\n                  download: download2,\n                  output,\n                  callId,\n                  executeLanguageModelCallInTelemetryContext: telemetryDispatcher.executeLanguageModelCall,\n                  toolsContext,\n                  experimental_sandbox: stepSandbox,\n                  onLanguageModelCallStart: filterNullable2(\n                    onLanguageModelCallStart,\n                    telemetryDispatcher.onLanguageModelCallStart\n                  ),\n                  onLanguageModelCallEnd: filterNullable2(\n                    onLanguageModelCallEnd,\n                    telemetryDispatcher.onLanguageModelCallEnd\n                  ),\n                  onStart: async ({ promptMessages }) => {\n                    var _a25, _b3;\n                    await notify({\n                      event: {\n                        callId,\n                        provider: stepModel.provider,\n                        modelId: stepModel.modelId,\n                        stepNumber: recordedSteps.length,\n                        instructions: stepInstructions,\n                        messages: stepMessages,\n                        tools,\n                        toolChoice: (_a25 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _a25 : toolChoice,\n                        activeTools: (_b3 = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _b3 : activeTools,\n                        toolOrder: stepToolOrder,\n                        steps: [...recordedSteps],\n                        providerOptions: stepProviderOptions,\n                        runtimeContext,\n                        toolsContext,\n                        output,\n                        promptMessages,\n                        stepTools,\n                        stepToolChoice\n                      },\n                      callbacks: [onStepStart, telemetryDispatcher.onStepStart]\n                    });\n                  },\n                  _internal: {\n                    now: now2\n                  },\n                  ...callSettings\n                });\n              }\n            )\n          );\n          const streamAfterToolCallbackInvocation = invokeToolCallbacksFromStream({\n            stream: languageModelStream,\n            tools,\n            stepInputMessages: stepMessages,\n            abortSignal,\n            runtimeContext\n          });\n          const runInTracingChannelSpanInStep = telemetryDispatcher.runInTracingChannelSpan == null ? void 0 : (options) => runInStepTracingChannelContext(\n            () => telemetryDispatcher.runInTracingChannelSpan(options)\n          );\n          const streamWithToolResults = executeToolsFromStream({\n            stream: streamAfterToolCallbackInvocation,\n            tools,\n            callId,\n            messages: stepMessages,\n            abortSignal,\n            timeout,\n            experimental_sandbox: stepSandbox,\n            toolsContext,\n            toolApproval,\n            runtimeContext,\n            toolApprovalSecret: experimental_toolApprovalSecret,\n            generateId: generateId2,\n            // the callbacks need to be passed down and handled by executeToolCall\n            // to guarantee that the onToolExecutionStart callback is invoked before the tool execute function\n            onToolExecutionStart: filterNullable2(\n              onToolExecutionStart,\n              telemetryDispatcher.onToolExecutionStart\n            ),\n            onToolExecutionEnd: filterNullable2(\n              onToolExecutionEnd,\n              telemetryDispatcher.onToolExecutionEnd\n            ),\n            executeToolInTelemetryContext: telemetryDispatcher.executeTool,\n            runInTracingChannelSpan: runInTracingChannelSpanInStep\n          });\n          const stepRequest = {\n            ...request,\n            body: include.requestBody ? request == null ? void 0 : request.body : void 0,\n            messages: include.requestMessages ? cloneModelMessages(stepMessages) : void 0\n          };\n          recordedRequestMessages = (_l = stepRequest.messages) != null ? _l : [];\n          const stepToolCalls = [];\n          const stepToolOutputs = [];\n          const stepToolApprovalResponses = [];\n          let warnings;\n          let stepFinishReason = \"other\";\n          let stepRawFinishReason = void 0;\n          let hasReceivedTerminalChunk = false;\n          let hasReceivedOutputChunk = false;\n          let stepUsage = createNullLanguageModelUsage();\n          let stepProviderMetadata;\n          let stepFirstChunk = true;\n          let modelCallPerformance = {\n            responseTimeMs: 0,\n            effectiveOutputTokensPerSecond: 0,\n            outputTokensPerSecond: void 0,\n            inputTokensPerSecond: void 0,\n            effectiveTotalTokensPerSecond: 0,\n            timeToFirstOutputMs: void 0,\n            timeBetweenOutputChunksMs: void 0\n          };\n          const toolExecutionMs = {};\n          let stepResponse = {\n            id: generateId2(),\n            timestamp: /* @__PURE__ */ new Date(),\n            modelId: model.modelId\n          };\n          self.addStream(\n            streamWithToolResults.pipeThrough(\n              new TransformStream({\n                async transform(chunk, controller) {\n                  var _a24, _b2, _c2;\n                  resetChunkTimeout();\n                  if (chunk.type === \"model-call-start\") {\n                    warnings = chunk.warnings;\n                    return;\n                  }\n                  if (stepFirstChunk) {\n                    stepFirstChunk = false;\n                    controller.enqueue({\n                      type: \"start-step\",\n                      request: stepRequest,\n                      warnings: warnings != null ? warnings : []\n                    });\n                  }\n                  const chunkType = chunk.type;\n                  if (isOutputChunkType[chunkType]) {\n                    hasReceivedOutputChunk = true;\n                  }\n                  switch (chunkType) {\n                    case \"file\":\n                    case \"custom\":\n                    case \"source\":\n                    case \"text-start\":\n                    case \"text-end\":\n                    case \"reasoning-start\":\n                    case \"reasoning-end\":\n                    case \"reasoning-delta\":\n                    case \"reasoning-file\":\n                    case \"tool-input-start\":\n                    case \"tool-input-end\":\n                    case \"tool-input-delta\":\n                    case \"tool-approval-request\": {\n                      controller.enqueue(chunk);\n                      break;\n                    }\n                    case \"text-delta\": {\n                      if (chunk.text.length > 0) {\n                        controller.enqueue(chunk);\n                      }\n                      break;\n                    }\n                    case \"tool-call\": {\n                      controller.enqueue(chunk);\n                      stepToolCalls.push(chunk);\n                      break;\n                    }\n                    case \"tool-approval-response\": {\n                      controller.enqueue(chunk);\n                      stepToolApprovalResponses.push(chunk);\n                      break;\n                    }\n                    case \"tool-result\": {\n                      controller.enqueue(chunk);\n                      if (!chunk.preliminary) {\n                        stepToolOutputs.push(chunk);\n                      }\n                      break;\n                    }\n                    case \"tool-error\": {\n                      controller.enqueue(chunk);\n                      stepToolOutputs.push(chunk);\n                      break;\n                    }\n                    case \"tool-execution-end\": {\n                      toolExecutionMs[chunk.toolCallId] = chunk.toolExecutionMs;\n                      break;\n                    }\n                    case \"model-call-response-metadata\": {\n                      stepResponse = {\n                        id: (_a24 = chunk.id) != null ? _a24 : stepResponse.id,\n                        timestamp: (_b2 = chunk.timestamp) != null ? _b2 : stepResponse.timestamp,\n                        modelId: (_c2 = chunk.modelId) != null ? _c2 : stepResponse.modelId\n                      };\n                      break;\n                    }\n                    case \"model-call-end\": {\n                      hasReceivedTerminalChunk = true;\n                      stepUsage = chunk.usage;\n                      stepFinishReason = chunk.finishReason;\n                      stepRawFinishReason = chunk.rawFinishReason;\n                      stepProviderMetadata = chunk.providerMetadata;\n                      modelCallPerformance = chunk.performance;\n                      break;\n                    }\n                    case \"error\": {\n                      hasReceivedTerminalChunk = true;\n                      controller.enqueue(chunk);\n                      stepFinishReason = \"error\";\n                      break;\n                    }\n                    case \"raw\": {\n                      if (include.rawChunks) {\n                        controller.enqueue(chunk);\n                      }\n                      break;\n                    }\n                    default: {\n                      const exhaustiveCheck = chunkType;\n                      throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n                    }\n                  }\n                },\n                // invoke onEnd callback and resolve toolResults promise when the stream is about to close:\n                async flush(controller) {\n                  if (!hasReceivedTerminalChunk && !hasReceivedOutputChunk) {\n                    controller.enqueue({\n                      type: \"error\",\n                      error: new NoOutputGeneratedError({\n                        message: \"No output generated. The model stream ended without a finish chunk.\"\n                      })\n                    });\n                    clearStepTimeout();\n                    clearChunkTimeout();\n                    self.closeStream();\n                    return;\n                  }\n                  const stepTimeMs = now2() - stepStartTimestampMs;\n                  const finishStepPart = {\n                    type: \"finish-step\",\n                    finishReason: stepFinishReason,\n                    rawFinishReason: stepRawFinishReason,\n                    usage: stepUsage,\n                    performance: {\n                      stepTimeMs,\n                      toolExecutionMs,\n                      ...modelCallPerformance\n                    },\n                    providerMetadata: stepProviderMetadata,\n                    response: {\n                      ...stepResponse,\n                      headers: response == null ? void 0 : response.headers\n                    }\n                  };\n                  controller.enqueue(finishStepPart);\n                  const combinedUsage = addLanguageModelUsage(usage, stepUsage);\n                  await stepFinish.promise;\n                  const clientToolCalls = stepToolCalls.filter(\n                    (toolCall) => toolCall.providerExecuted !== true\n                  );\n                  const clientToolOutputs = stepToolOutputs.filter(\n                    (toolOutput) => toolOutput.providerExecuted !== true\n                  );\n                  const deniedToolApprovalResponses = stepToolApprovalResponses.filter(\n                    (toolApprovalResponse) => toolApprovalResponse.approved === false\n                  );\n                  for (const toolCall of stepToolCalls) {\n                    if (toolCall.providerExecuted !== true)\n                      continue;\n                    const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n                    if ((tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults) {\n                      const hasResultInStep = stepToolOutputs.some(\n                        (output2) => (output2.type === \"tool-result\" || output2.type === \"tool-error\") && output2.toolCallId === toolCall.toolCallId\n                      );\n                      if (!hasResultInStep) {\n                        pendingDeferredToolCalls.set(toolCall.toolCallId, {\n                          toolName: toolCall.toolName\n                        });\n                      }\n                    }\n                  }\n                  for (const output2 of stepToolOutputs) {\n                    if (output2.type === \"tool-result\" || output2.type === \"tool-error\") {\n                      pendingDeferredToolCalls.delete(output2.toolCallId);\n                    }\n                  }\n                  clearStepTimeout();\n                  clearChunkTimeout();\n                  if (\n                    // Continue if:\n                    // 1. There are client tool calls that have all been executed or denied, OR\n                    // 2. There are pending deferred results from provider-executed tools, OR\n                    (clientToolCalls.length > 0 && clientToolCalls.length === clientToolOutputs.length + deniedToolApprovalResponses.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:\n                    !await isStopConditionMet({\n                      stopConditions,\n                      steps: recordedSteps\n                    })\n                  ) {\n                    try {\n                      await runInStreamTextTracingChannelContext(\n                        () => streamStep({\n                          currentStep: currentStep + 1,\n                          usage: combinedUsage\n                        })\n                      );\n                    } catch (error) {\n                      controller.enqueue({\n                        type: \"error\",\n                        error\n                      });\n                      self.closeStream();\n                    }\n                  } else {\n                    controller.enqueue({\n                      type: \"finish\",\n                      finishReason: stepFinishReason,\n                      rawFinishReason: stepRawFinishReason,\n                      totalUsage: combinedUsage\n                    });\n                    self.closeStream();\n                  }\n                }\n              })\n            )\n          );\n        } catch (error) {\n          clearStepTimeout();\n          clearChunkTimeout();\n          throw error;\n        }\n      }\n      await runInStreamTextTracingChannelContext(\n        () => (\n          // add the initial stream to the stitchable stream\n          streamStep({\n            currentStep: 0,\n            usage: createNullLanguageModelUsage()\n          })\n        )\n      );\n    })().catch(async (error) => {\n      var _a22;\n      await ((_a22 = telemetryDispatcher.onError) == null ? void 0 : _a22.call(telemetryDispatcher, { callId, error }));\n      self._initialResponseMessages.reject(error);\n      markPromiseAsHandled(self._initialResponseMessages.promise);\n      self.addStream(\n        new ReadableStream({\n          start(controller) {\n            controller.enqueue({ type: \"error\", error });\n            controller.close();\n          }\n        })\n      );\n      self.closeStream();\n    });\n  }\n  get steps() {\n    this.consumeStream();\n    return this._steps.promise;\n  }\n  get finalStep() {\n    return this.steps.then((steps) => steps.at(-1));\n  }\n  get content() {\n    return this.steps.then((steps) => steps.flatMap((step) => step.content));\n  }\n  get warnings() {\n    return this.steps.then((steps) => steps.flatMap((step) => {\n      var _a22;\n      return (_a22 = step.warnings) != null ? _a22 : [];\n    }));\n  }\n  get providerMetadata() {\n    return this.finalStep.then((step) => step.providerMetadata);\n  }\n  get text() {\n    return this.finalStep.then((step) => step.text);\n  }\n  get reasoningText() {\n    return this.finalStep.then((step) => step.reasoningText);\n  }\n  get reasoning() {\n    return this.finalStep.then(\n      (step) => convertToReasoningOutputs(step.reasoning)\n    );\n  }\n  get sources() {\n    return this.steps.then((steps) => steps.flatMap((step) => step.sources));\n  }\n  get files() {\n    return this.steps.then((steps) => steps.flatMap((step) => step.files));\n  }\n  get toolCalls() {\n    return this.steps.then((steps) => steps.flatMap((step) => step.toolCalls));\n  }\n  get staticToolCalls() {\n    return this.steps.then(\n      (steps) => steps.flatMap((step) => step.staticToolCalls)\n    );\n  }\n  get dynamicToolCalls() {\n    return this.steps.then(\n      (steps) => steps.flatMap((step) => step.dynamicToolCalls)\n    );\n  }\n  get toolResults() {\n    return this.steps.then((steps) => steps.flatMap((step) => step.toolResults));\n  }\n  get staticToolResults() {\n    return this.steps.then(\n      (steps) => steps.flatMap((step) => step.staticToolResults)\n    );\n  }\n  get dynamicToolResults() {\n    return this.steps.then(\n      (steps) => steps.flatMap((step) => step.dynamicToolResults)\n    );\n  }\n  get usage() {\n    return this.totalUsage;\n  }\n  get request() {\n    return this.finalStep.then((step) => step.request);\n  }\n  get response() {\n    return this.finalStep.then((step) => step.response);\n  }\n  get responseMessages() {\n    return Promise.all([\n      this._initialResponseMessages.promise,\n      this.steps\n    ]).then(([initialResponseMessages, steps]) => [\n      ...initialResponseMessages,\n      ...steps.flatMap((step) => step.response.messages)\n    ]);\n  }\n  get totalUsage() {\n    this.consumeStream();\n    return this._totalUsage.promise;\n  }\n  get finishReason() {\n    this.consumeStream();\n    return this._finishReason.promise;\n  }\n  get rawFinishReason() {\n    this.consumeStream();\n    return this._rawFinishReason.promise;\n  }\n  /**\n   * Split out a new stream from the original stream.\n   * The original stream is replaced to allow for further splitting,\n   * since we do not know how many times the stream will be split.\n   *\n   * Note: this leads to buffering the stream content on the server.\n   * However, the LLM results are expected to be small enough to not cause issues.\n   */\n  teeStream() {\n    const [stream1, stream2] = this.baseStream.tee();\n    this.baseStream = stream2;\n    return stream1;\n  }\n  get textStream() {\n    return createAsyncIterableStream(toTextStream({ stream: this.stream }));\n  }\n  get stream() {\n    return createAsyncIterableStream(\n      this.teeStream().pipeThrough(\n        new TransformStream({\n          transform({ part }, controller) {\n            controller.enqueue(part);\n          }\n        })\n      )\n    );\n  }\n  get fullStream() {\n    return this.stream;\n  }\n  rejectResultPromises(error) {\n    this.rejectResultPromise({ delayedPromise: this._finishReason, error });\n    this.rejectResultPromise({ delayedPromise: this._rawFinishReason, error });\n    this.rejectResultPromise({ delayedPromise: this._totalUsage, error });\n    this.rejectResultPromise({ delayedPromise: this._steps, error });\n    this.rejectResultPromise({\n      delayedPromise: this._initialResponseMessages,\n      error\n    });\n  }\n  rejectResultPromise({\n    delayedPromise,\n    error\n  }) {\n    if (delayedPromise.isPending()) {\n      delayedPromise.reject(error);\n      markPromiseAsHandled(delayedPromise.promise);\n    }\n  }\n  async consumeStream(options) {\n    var _a22;\n    try {\n      await consumeStream({\n        stream: this.stream,\n        onError: (error) => {\n          var _a23;\n          this.rejectResultPromises(error);\n          (_a23 = options == null ? void 0 : options.onError) == null ? void 0 : _a23.call(options, error);\n        }\n      });\n    } catch (error) {\n      this.rejectResultPromises(error);\n      (_a22 = options == null ? void 0 : options.onError) == null ? void 0 : _a22.call(options, error);\n    }\n  }\n  get experimental_partialOutputStream() {\n    return this.partialOutputStream;\n  }\n  get partialOutputStream() {\n    return createAsyncIterableStream(\n      this.teeStream().pipeThrough(\n        new TransformStream({\n          transform({ partialOutput }, controller) {\n            if (partialOutput != null) {\n              controller.enqueue(partialOutput);\n            }\n          }\n        })\n      )\n    );\n  }\n  get elementStream() {\n    var _a22, _b, _c;\n    const transform = (_a22 = this.outputSpecification) == null ? void 0 : _a22.createElementStreamTransform();\n    if (transform == null) {\n      throw new UnsupportedFunctionalityError2({\n        functionality: `element streams in ${(_c = (_b = this.outputSpecification) == null ? void 0 : _b.name) != null ? _c : \"text\"} mode`\n      });\n    }\n    return createAsyncIterableStream(this.teeStream().pipeThrough(transform));\n  }\n  get output() {\n    return this.finalStep.then((step) => {\n      var _a22;\n      const output = (_a22 = this.outputSpecification) != null ? _a22 : text();\n      return output.parseCompleteOutput(\n        { text: step.text },\n        {\n          response: step.response,\n          usage: step.usage,\n          finishReason: step.finishReason\n        }\n      );\n    });\n  }\n  toUIMessageStream({\n    originalMessages,\n    generateMessageId,\n    onEnd,\n    onFinish,\n    messageMetadata,\n    sendReasoning,\n    sendSources,\n    sendStart,\n    sendFinish,\n    onError\n  } = {}) {\n    return createAsyncIterableStream(\n      toUIMessageStream({\n        stream: this.stream,\n        tools: this.tools,\n        originalMessages,\n        generateMessageId,\n        onEnd: onEnd != null ? onEnd : onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendStart,\n        sendFinish,\n        onError\n      })\n    );\n  }\n  pipeUIMessageStreamToResponse(response, {\n    originalMessages,\n    generateMessageId,\n    onEnd,\n    onFinish,\n    messageMetadata,\n    sendReasoning,\n    sendSources,\n    sendFinish,\n    sendStart,\n    onError,\n    ...init\n  } = {}) {\n    pipeUIMessageStreamToResponse({\n      response,\n      stream: this.toUIMessageStream({\n        originalMessages,\n        generateMessageId,\n        onEnd: onEnd != null ? onEnd : onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendFinish,\n        sendStart,\n        onError\n      }),\n      ...init\n    });\n  }\n  pipeTextStreamToResponse(response, init) {\n    pipeTextStreamToResponse({\n      response,\n      stream: this.textStream,\n      ...init\n    });\n  }\n  toUIMessageStreamResponse({\n    originalMessages,\n    generateMessageId,\n    onEnd,\n    onFinish,\n    messageMetadata,\n    sendReasoning,\n    sendSources,\n    sendFinish,\n    sendStart,\n    onError,\n    ...init\n  } = {}) {\n    return createUIMessageStreamResponse({\n      stream: this.toUIMessageStream({\n        originalMessages,\n        generateMessageId,\n        onEnd: onEnd != null ? onEnd : onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendFinish,\n        sendStart,\n        onError\n      }),\n      ...init\n    });\n  }\n  toTextStreamResponse(init) {\n    return createTextStreamResponse({\n      stream: this.textStream,\n      ...init\n    });\n  }\n};\n\n// src/agent/tool-loop-agent.ts\nvar ToolLoopAgent = class {\n  constructor(settings) {\n    this.version = \"agent-v1\";\n    const { onFinish, onEnd = onFinish } = settings;\n    this.settings = { ...settings, onEnd };\n  }\n  /**\n   * The id of the agent.\n   */\n  get id() {\n    return this.settings.id;\n  }\n  /**\n   * The tools that the agent can use.\n   */\n  get tools() {\n    return this.settings.tools;\n  }\n  async prepareCall(options) {\n    var _a22, _b, _c, _d;\n    if (this.settings.callOptionsSchema != null && options.options !== void 0) {\n      const validatedOptions = await validateTypes3({\n        value: options.options,\n        schema: this.settings.callOptionsSchema,\n        context: { field: \"options\" }\n      });\n      options = { ...options, options: validatedOptions };\n    }\n    const {\n      onStart: _settingsStableOnStart,\n      experimental_onStart: _settingsExperimentalOnStart,\n      onStepStart: _settingsStableOnStepStart,\n      experimental_onStepStart: _settingsExperimentalOnStepStart,\n      onToolExecutionStart: _settingsOnToolExecutionStart,\n      onToolExecutionEnd: _settingsOnToolExecutionEnd,\n      onStepEnd: _settingsOnStepEnd,\n      onStepFinish: _settingsOnStepFinish,\n      onFinish: _settingsOnFinish,\n      onEnd: _settingsOnEnd,\n      ...settingsWithoutCallbacks\n    } = this.settings;\n    const baseCallArgs = {\n      ...settingsWithoutCallbacks,\n      stopWhen: (_a22 = this.settings.stopWhen) != null ? _a22 : isStepCount(20),\n      ...options\n    };\n    const preparedCallArgs = (_d = await ((_c = (_b = this.settings).prepareCall) == null ? void 0 : _c.call(\n      _b,\n      baseCallArgs\n    ))) != null ? _d : baseCallArgs;\n    const {\n      instructions,\n      allowSystemInMessages,\n      messages,\n      prompt,\n      runtimeContext,\n      ...callArgs\n    } = preparedCallArgs;\n    const promptArgs = {\n      instructions,\n      allowSystemInMessages,\n      messages,\n      prompt\n    };\n    if (runtimeContext === void 0) {\n      return {\n        ...callArgs,\n        ...promptArgs\n      };\n    }\n    return {\n      ...callArgs,\n      runtimeContext,\n      ...promptArgs\n    };\n  }\n  /**\n   * Tags outgoing requests so usage can be attributed to ToolLoopAgent. Chains\n   * with the `ai/<version>` and `ai-sdk/<provider>/<version>` suffixes added\n   * downstream by generateText/streamText and the provider.\n   */\n  agentHeaders(preparedCall) {\n    var _a22;\n    return withUserAgentSuffix3(\n      (_a22 = preparedCall.headers) != null ? _a22 : {},\n      \"ai-sdk-agent/tool-loop\"\n    );\n  }\n  /**\n   * Generates an output from the agent (non-streaming).\n   */\n  async generate({\n    abortSignal,\n    timeout,\n    experimental_sandbox: sandbox,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onToolExecutionStart,\n    onToolExecutionEnd,\n    onStepEnd,\n    onStepFinish,\n    onFinish,\n    onEnd = onFinish,\n    ...options\n  }) {\n    var _a22, _b, _c;\n    const generate = generateText;\n    const preparedCall = await this.prepareCall({\n      ...options,\n      experimental_sandbox: sandbox\n    });\n    const callbackArgs = {\n      abortSignal,\n      timeout,\n      experimental_sandbox: sandbox,\n      onStart: mergeCallbacks(\n        (_a22 = this.settings.onStart) != null ? _a22 : this.settings.experimental_onStart,\n        onStart != null ? onStart : experimental_onStart\n      ),\n      onStepStart: mergeCallbacks(\n        (_b = this.settings.onStepStart) != null ? _b : this.settings.experimental_onStepStart,\n        onStepStart != null ? onStepStart : experimental_onStepStart\n      ),\n      onToolExecutionStart: mergeCallbacks(\n        this.settings.onToolExecutionStart,\n        onToolExecutionStart\n      ),\n      onToolExecutionEnd: mergeCallbacks(\n        this.settings.onToolExecutionEnd,\n        onToolExecutionEnd\n      ),\n      onStepEnd: mergeCallbacks(\n        (_c = this.settings.onStepEnd) != null ? _c : this.settings.onStepFinish,\n        onStepEnd != null ? onStepEnd : onStepFinish\n      ),\n      onEnd: mergeCallbacks(this.settings.onEnd, onEnd)\n    };\n    return await generate({\n      ...preparedCall,\n      ...callbackArgs,\n      headers: this.agentHeaders(preparedCall)\n    });\n  }\n  /**\n   * Streams an output from the agent (streaming).\n   */\n  async stream({\n    abortSignal,\n    timeout,\n    experimental_sandbox: sandbox,\n    experimental_transform,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onToolExecutionStart,\n    onToolExecutionEnd,\n    onStepEnd,\n    onStepFinish,\n    onFinish,\n    onEnd = onFinish,\n    ...options\n  }) {\n    var _a22, _b, _c;\n    const stream = streamText;\n    const preparedCall = await this.prepareCall({\n      ...options,\n      experimental_sandbox: sandbox\n    });\n    const callbackArgs = {\n      abortSignal,\n      timeout,\n      experimental_sandbox: sandbox,\n      experimental_transform,\n      onStart: mergeCallbacks(\n        (_a22 = this.settings.onStart) != null ? _a22 : this.settings.experimental_onStart,\n        onStart != null ? onStart : experimental_onStart\n      ),\n      onStepStart: mergeCallbacks(\n        (_b = this.settings.onStepStart) != null ? _b : this.settings.experimental_onStepStart,\n        onStepStart != null ? onStepStart : experimental_onStepStart\n      ),\n      onToolExecutionStart: mergeCallbacks(\n        this.settings.onToolExecutionStart,\n        onToolExecutionStart\n      ),\n      onToolExecutionEnd: mergeCallbacks(\n        this.settings.onToolExecutionEnd,\n        onToolExecutionEnd\n      ),\n      onStepEnd: mergeCallbacks(\n        (_c = this.settings.onStepEnd) != null ? _c : this.settings.onStepFinish,\n        onStepEnd != null ? onStepEnd : onStepFinish\n      ),\n      onEnd: mergeCallbacks(this.settings.onEnd, onEnd)\n    };\n    return await stream({\n      ...preparedCall,\n      ...callbackArgs,\n      headers: this.agentHeaders(preparedCall)\n    });\n  }\n};\n\n// src/ui-message-stream/create-ui-message-stream.ts\nimport {\n  generateId as generateIdFunc\n} from \"@ai-sdk/provider-utils\";\nfunction createUIMessageStream({\n  execute,\n  onError = () => \"An error occurred.\",\n  // prevent leaking server error details to the client by default\n  originalMessages,\n  onStepEnd,\n  onStepFinish,\n  onEnd,\n  onFinish,\n  generateId: generateId2 = generateIdFunc\n}) {\n  let controller;\n  const ongoingStreamPromises = [];\n  const stream = new ReadableStream({\n    start(controllerArg) {\n      controller = controllerArg;\n    }\n  });\n  function safeEnqueue(data) {\n    try {\n      controller.enqueue(data);\n    } catch (e) {\n    }\n  }\n  try {\n    const result = execute({\n      writer: {\n        write(part) {\n          safeEnqueue(part);\n        },\n        merge(streamArg) {\n          ongoingStreamPromises.push(\n            (async () => {\n              const reader = streamArg.getReader();\n              while (true) {\n                const { done, value } = await reader.read();\n                if (done)\n                  break;\n                safeEnqueue(value);\n              }\n            })().catch((error) => {\n              safeEnqueue({\n                type: \"error\",\n                errorText: onError(error)\n              });\n            })\n          );\n        },\n        onError\n      }\n    });\n    if (result) {\n      ongoingStreamPromises.push(\n        result.catch((error) => {\n          safeEnqueue({\n            type: \"error\",\n            errorText: onError(error)\n          });\n        })\n      );\n    }\n  } catch (error) {\n    safeEnqueue({\n      type: \"error\",\n      errorText: onError(error)\n    });\n  }\n  const waitForStreams = new Promise(async (resolve3) => {\n    while (ongoingStreamPromises.length > 0) {\n      await ongoingStreamPromises.shift();\n    }\n    resolve3();\n  });\n  waitForStreams.finally(() => {\n    try {\n      controller.close();\n    } catch (e) {\n    }\n  });\n  return handleUIMessageStreamFinish({\n    stream,\n    messageId: generateId2(),\n    originalMessages,\n    onStepEnd: onStepEnd != null ? onStepEnd : onStepFinish,\n    onEnd: onEnd != null ? onEnd : onFinish,\n    onError\n  });\n}\n\n// src/ui-message-stream/read-ui-message-stream.ts\nfunction readUIMessageStream({\n  message,\n  stream,\n  onError,\n  terminateOnError = false\n}) {\n  var _a22;\n  let controller;\n  let hasErrored = false;\n  const outputStream = new ReadableStream({\n    start(controllerParam) {\n      controller = controllerParam;\n    }\n  });\n  const state = createStreamingUIMessageState({\n    messageId: (_a22 = message == null ? void 0 : message.id) != null ? _a22 : \"\",\n    lastMessage: message\n  });\n  const handleError = (error) => {\n    onError == null ? void 0 : onError(error);\n    if (!hasErrored && terminateOnError) {\n      hasErrored = true;\n      controller == null ? void 0 : controller.error(error);\n    }\n  };\n  consumeStream({\n    stream: processUIMessageStream({\n      stream,\n      runUpdateMessageJob(job) {\n        return job({\n          state,\n          write: () => {\n            controller == null ? void 0 : controller.enqueue(structuredClone(state.message));\n          }\n        });\n      },\n      onError: handleError\n    }),\n    onError: handleError\n  }).finally(() => {\n    if (!hasErrored) {\n      controller == null ? void 0 : controller.close();\n    }\n  });\n  return createAsyncIterableStream(outputStream);\n}\n\n// src/ui/convert-to-model-messages.ts\nimport {\n  isNonNullable\n} from \"@ai-sdk/provider-utils\";\nasync function convertToModelMessages(messages, options) {\n  const modelMessages = [];\n  if (options == null ? void 0 : options.ignoreIncompleteToolCalls) {\n    messages = messages.map((message) => ({\n      ...message,\n      parts: message.parts.filter(\n        (part) => !isToolUIPart(part) || part.state !== \"input-streaming\" && part.state !== \"input-available\"\n      )\n    }));\n  }\n  for (const message of messages) {\n    switch (message.role) {\n      case \"system\": {\n        const textParts = message.parts.filter(\n          (part) => part.type === \"text\"\n        );\n        const providerMetadata = textParts.reduce((acc, part) => {\n          if (part.providerMetadata != null) {\n            return { ...acc, ...part.providerMetadata };\n          }\n          return acc;\n        }, {});\n        modelMessages.push({\n          role: \"system\",\n          content: textParts.map((part) => part.text).join(\"\"),\n          ...Object.keys(providerMetadata).length > 0 ? { providerOptions: providerMetadata } : {}\n        });\n        break;\n      }\n      case \"user\": {\n        modelMessages.push({\n          role: \"user\",\n          content: message.parts.map((part) => {\n            var _a22;\n            if (isTextUIPart(part)) {\n              return {\n                type: \"text\",\n                text: part.text,\n                ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n              };\n            }\n            if (isFileUIPart(part)) {\n              return {\n                type: \"file\",\n                mediaType: part.mediaType,\n                filename: part.filename,\n                data: part.providerReference != null ? {\n                  type: \"reference\",\n                  reference: part.providerReference\n                } : { type: \"url\", url: new URL(part.url) },\n                ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n              };\n            }\n            if (isDataUIPart(part)) {\n              return (_a22 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a22.call(\n                options,\n                part\n              );\n            }\n          }).filter(isNonNullable)\n        });\n        break;\n      }\n      case \"assistant\": {\n        if (message.parts != null) {\n          let block = [];\n          async function processBlock() {\n            var _a22, _b, _c, _d, _e, _f, _g, _h, _i;\n            if (block.length === 0) {\n              return;\n            }\n            const content = [];\n            for (const part of block) {\n              if (isTextUIPart(part)) {\n                content.push({\n                  type: \"text\",\n                  text: part.text,\n                  ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n                });\n              } else if (isCustomContentUIPart(part)) {\n                content.push({\n                  type: \"custom\",\n                  kind: part.kind,\n                  ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n                });\n              } else if (isFileUIPart(part)) {\n                content.push({\n                  type: \"file\",\n                  mediaType: part.mediaType,\n                  filename: part.filename,\n                  data: part.providerReference != null ? {\n                    type: \"reference\",\n                    reference: part.providerReference\n                  } : { type: \"url\", url: new URL(part.url) },\n                  ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n                });\n              } else if (isReasoningFileUIPart(part)) {\n                content.push({\n                  type: \"reasoning-file\",\n                  data: { type: \"url\", url: new URL(part.url) },\n                  mediaType: part.mediaType,\n                  providerOptions: part.providerMetadata\n                });\n              } else if (isReasoningUIPart(part)) {\n                content.push({\n                  type: \"reasoning\",\n                  text: part.text,\n                  providerOptions: part.providerMetadata\n                });\n              } else if (isToolUIPart(part)) {\n                const toolName = getToolName(part);\n                if (part.state !== \"input-streaming\") {\n                  content.push({\n                    type: \"tool-call\",\n                    toolCallId: part.toolCallId,\n                    toolName,\n                    input: part.state === \"output-error\" ? (_a22 = part.input) != null ? _a22 : \"rawInput\" in part ? part.rawInput : void 0 : part.input,\n                    providerExecuted: part.providerExecuted,\n                    ...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n                  });\n                  if (part.approval != null) {\n                    content.push({\n                      type: \"tool-approval-request\",\n                      approvalId: part.approval.id,\n                      toolCallId: part.toolCallId,\n                      isAutomatic: part.approval.isAutomatic,\n                      ...part.approval.signature != null ? { signature: part.approval.signature } : {}\n                    });\n                  }\n                  if (part.providerExecuted === true && part.state !== \"approval-responded\" && (part.state === \"output-available\" || part.state === \"output-error\")) {\n                    const resultProviderMetadata = (_b = part.resultProviderMetadata) != null ? _b : part.callProviderMetadata;\n                    content.push({\n                      type: \"tool-result\",\n                      toolCallId: part.toolCallId,\n                      toolName,\n                      output: await createToolModelOutput({\n                        toolCallId: part.toolCallId,\n                        input: part.input,\n                        output: part.state === \"output-error\" ? part.errorText : part.output,\n                        tool: (_c = options == null ? void 0 : options.tools) == null ? void 0 : _c[toolName],\n                        errorMode: part.state === \"output-error\" ? \"json\" : \"none\"\n                      }),\n                      ...resultProviderMetadata != null ? { providerOptions: resultProviderMetadata } : {}\n                    });\n                  }\n                }\n              } else if (isDataUIPart(part)) {\n                const dataPart = (_d = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _d.call(\n                  options,\n                  part\n                );\n                if (dataPart != null) {\n                  content.push(dataPart);\n                }\n              } else {\n                const _exhaustiveCheck = part;\n                throw new Error(`Unsupported part: ${_exhaustiveCheck}`);\n              }\n            }\n            modelMessages.push({\n              role: \"assistant\",\n              content\n            });\n            const toolParts = block.filter(\n              (part) => {\n                var _a23;\n                return isToolUIPart(part) && (part.providerExecuted !== true || ((_a23 = part.approval) == null ? void 0 : _a23.approved) != null);\n              }\n            );\n            if (toolParts.length > 0) {\n              {\n                const content2 = [];\n                for (const toolPart of toolParts) {\n                  if (((_e = toolPart.approval) == null ? void 0 : _e.approved) != null) {\n                    content2.push({\n                      type: \"tool-approval-response\",\n                      approvalId: toolPart.approval.id,\n                      approved: toolPart.approval.approved,\n                      reason: toolPart.approval.reason,\n                      providerExecuted: toolPart.providerExecuted\n                    });\n                  }\n                  if (toolPart.state === \"approval-responded\" && ((_f = toolPart.approval) == null ? void 0 : _f.approved) === false) {\n                    content2.push({\n                      type: \"tool-result\",\n                      toolCallId: toolPart.toolCallId,\n                      toolName: getToolName(toolPart),\n                      output: {\n                        type: \"execution-denied\",\n                        reason: toolPart.approval.reason\n                      },\n                      ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n                    });\n                  }\n                  if (toolPart.providerExecuted === true) {\n                    continue;\n                  }\n                  switch (toolPart.state) {\n                    case \"output-denied\": {\n                      content2.push({\n                        type: \"tool-result\",\n                        toolCallId: toolPart.toolCallId,\n                        toolName: getToolName(toolPart),\n                        output: {\n                          type: \"error-text\",\n                          value: (_h = (_g = toolPart.approval) == null ? void 0 : _g.reason) != null ? _h : \"Tool call execution denied.\"\n                        },\n                        ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n                      });\n                      break;\n                    }\n                    case \"output-error\":\n                    case \"output-available\": {\n                      const toolName = getToolName(toolPart);\n                      content2.push({\n                        type: \"tool-result\",\n                        toolCallId: toolPart.toolCallId,\n                        toolName,\n                        output: await createToolModelOutput({\n                          toolCallId: toolPart.toolCallId,\n                          input: toolPart.input,\n                          output: toolPart.state === \"output-error\" ? toolPart.errorText : toolPart.output,\n                          tool: (_i = options == null ? void 0 : options.tools) == null ? void 0 : _i[toolName],\n                          errorMode: toolPart.state === \"output-error\" ? \"text\" : \"none\"\n                        }),\n                        ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n                      });\n                      break;\n                    }\n                  }\n                }\n                if (content2.length > 0) {\n                  modelMessages.push({\n                    role: \"tool\",\n                    content: content2\n                  });\n                }\n              }\n            }\n            block = [];\n          }\n          for (const part of message.parts) {\n            if (isCustomContentUIPart(part) || isTextUIPart(part) || isReasoningUIPart(part) || isReasoningFileUIPart(part) || isFileUIPart(part) || isToolUIPart(part) || isDataUIPart(part)) {\n              block.push(part);\n            } else if (part.type === \"step-start\") {\n              await processBlock();\n            }\n          }\n          await processBlock();\n          break;\n        }\n        break;\n      }\n      default: {\n        const _exhaustiveCheck = message.role;\n        throw new MessageConversionError({\n          originalMessage: message,\n          message: `Unsupported role: ${_exhaustiveCheck}`\n        });\n      }\n    }\n  }\n  return modelMessages;\n}\n\n// src/ui/validate-ui-messages.ts\nimport { TypeValidationError as TypeValidationError3 } from \"@ai-sdk/provider\";\nimport {\n  lazySchema as lazySchema2,\n  validateTypes as validateTypes4,\n  zodSchema as zodSchema2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar toolMetadataSchema2 = z7.record(\n  z7.string(),\n  jsonValueSchema.optional()\n);\nvar providerReferenceSchema2 = z7.record(z7.string(), z7.string());\nvar uiMessagesSchema = lazySchema2(\n  () => zodSchema2(\n    z7.array(\n      z7.object({\n        id: z7.string(),\n        role: z7.enum([\"system\", \"user\", \"assistant\"]),\n        metadata: z7.unknown().optional(),\n        parts: z7.array(\n          z7.union([\n            z7.object({\n              type: z7.literal(\"text\"),\n              text: z7.string(),\n              state: z7.enum([\"streaming\", \"done\"]).optional(),\n              providerMetadata: providerMetadataSchema.optional()\n            }),\n            z7.object({\n              type: z7.literal(\"reasoning\"),\n              text: z7.string(),\n              state: z7.enum([\"streaming\", \"done\"]).optional(),\n              providerMetadata: providerMetadataSchema.optional()\n            }),\n            z7.object({\n              type: z7.literal(\"custom\"),\n              kind: z7.string(),\n              providerMetadata: providerMetadataSchema.optional()\n            }),\n            z7.object({\n              type: z7.literal(\"source-url\"),\n              sourceId: z7.string(),\n              url: z7.string(),\n              title: z7.string().optional(),\n              providerMetadata: providerMetadataSchema.optional()\n            }),\n            z7.object({\n              type: z7.literal(\"source-document\"),\n              sourceId: z7.string(),\n              mediaType: z7.string(),\n              title: z7.string(),\n              filename: z7.string().optional(),\n              providerMetadata: providerMetadataSchema.optional()\n            }),\n            z7.object({\n              type: z7.literal(\"file\"),\n              mediaType: z7.string(),\n              filename: z7.string().optional(),\n              url: z7.string(),\n              providerReference: providerReferenceSchema2.optional(),\n              providerMetadata: providerMetadataSchema.optional()\n            }),\n            z7.object({\n              type: z7.literal(\"reasoning-file\"),\n              mediaType: z7.string(),\n              url: z7.string(),\n              providerMetadata: providerMetadataSchema.optional()\n            }),\n            z7.object({\n              type: z7.literal(\"step-start\")\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"data-\"),\n              id: z7.string().optional(),\n              data: z7.unknown()\n            }),\n            z7.object({\n              type: z7.literal(\"dynamic-tool\"),\n              toolName: z7.string(),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"input-streaming\"),\n              input: z7.unknown().optional(),\n              providerExecuted: z7.boolean().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              approval: z7.never().optional()\n            }),\n            z7.object({\n              type: z7.literal(\"dynamic-tool\"),\n              toolName: z7.string(),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"input-available\"),\n              input: z7.unknown(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.never().optional()\n            }),\n            z7.object({\n              type: z7.literal(\"dynamic-tool\"),\n              toolName: z7.string(),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"approval-requested\"),\n              input: z7.unknown(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.never().optional(),\n                reason: z7.never().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              })\n            }),\n            z7.object({\n              type: z7.literal(\"dynamic-tool\"),\n              toolName: z7.string(),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"approval-responded\"),\n              input: z7.unknown(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.boolean(),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              })\n            }),\n            z7.object({\n              type: z7.literal(\"dynamic-tool\"),\n              toolName: z7.string(),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"output-available\"),\n              input: z7.unknown(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.unknown(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              resultProviderMetadata: providerMetadataSchema.optional(),\n              preliminary: z7.boolean().optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.literal(true),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              }).optional()\n            }),\n            z7.object({\n              type: z7.literal(\"dynamic-tool\"),\n              toolName: z7.string(),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"output-error\"),\n              input: z7.unknown().optional(),\n              rawInput: z7.unknown().optional(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.never().optional(),\n              errorText: z7.string(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              resultProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.literal(true),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              }).optional()\n            }),\n            z7.object({\n              type: z7.literal(\"dynamic-tool\"),\n              toolName: z7.string(),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"output-denied\"),\n              input: z7.unknown(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.literal(false),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              })\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"tool-\"),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"input-streaming\"),\n              providerExecuted: z7.boolean().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              input: z7.unknown().optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              approval: z7.never().optional()\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"tool-\"),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"input-available\"),\n              providerExecuted: z7.boolean().optional(),\n              input: z7.unknown(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.never().optional()\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"tool-\"),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"approval-requested\"),\n              input: z7.unknown(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.never().optional(),\n                reason: z7.never().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              })\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"tool-\"),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"approval-responded\"),\n              input: z7.unknown(),\n              providerExecuted: z7.boolean().optional(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.boolean(),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              })\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"tool-\"),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"output-available\"),\n              providerExecuted: z7.boolean().optional(),\n              input: z7.unknown(),\n              output: z7.unknown(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              resultProviderMetadata: providerMetadataSchema.optional(),\n              preliminary: z7.boolean().optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.literal(true),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              }).optional()\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"tool-\"),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"output-error\"),\n              providerExecuted: z7.boolean().optional(),\n              input: z7.unknown().optional(),\n              rawInput: z7.unknown().optional(),\n              output: z7.never().optional(),\n              errorText: z7.string(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              resultProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.literal(true),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              }).optional()\n            }),\n            z7.object({\n              type: z7.string().startsWith(\"tool-\"),\n              toolCallId: z7.string(),\n              toolMetadata: toolMetadataSchema2.optional(),\n              state: z7.literal(\"output-denied\"),\n              providerExecuted: z7.boolean().optional(),\n              input: z7.unknown(),\n              output: z7.never().optional(),\n              errorText: z7.never().optional(),\n              callProviderMetadata: providerMetadataSchema.optional(),\n              approval: z7.object({\n                id: z7.string(),\n                approved: z7.literal(false),\n                reason: z7.string().optional(),\n                isAutomatic: z7.boolean().optional(),\n                signature: z7.string().optional()\n              })\n            })\n          ])\n        ).nonempty(\"Message must contain at least one part\")\n      })\n    ).nonempty(\"Messages array must not be empty\")\n  )\n);\nasync function safeValidateUIMessages({\n  messages,\n  metadataSchema,\n  dataSchemas,\n  tools\n}) {\n  try {\n    if (messages == null) {\n      return {\n        success: false,\n        error: new InvalidArgumentError({\n          parameter: \"messages\",\n          value: messages,\n          message: \"messages parameter must be provided\"\n        })\n      };\n    }\n    const validatedMessages = await validateTypes4({\n      value: messages,\n      schema: uiMessagesSchema\n    });\n    if (metadataSchema) {\n      for (const [msgIdx, message] of validatedMessages.entries()) {\n        await validateTypes4({\n          value: message.metadata,\n          schema: metadataSchema,\n          context: {\n            field: `messages[${msgIdx}].metadata`,\n            entityId: message.id\n          }\n        });\n      }\n    }\n    if (dataSchemas || tools) {\n      for (const [msgIdx, message] of validatedMessages.entries()) {\n        for (const [partIdx, part] of message.parts.entries()) {\n          if (dataSchemas && part.type.startsWith(\"data-\")) {\n            const dataPart = part;\n            const dataName = dataPart.type.slice(5);\n            const dataSchema = dataSchemas[dataName];\n            if (!dataSchema) {\n              return {\n                success: false,\n                error: new TypeValidationError3({\n                  value: dataPart.data,\n                  cause: `No data schema found for data part ${dataName}`,\n                  context: {\n                    field: `messages[${msgIdx}].parts[${partIdx}].data`,\n                    entityName: dataName,\n                    entityId: dataPart.id\n                  }\n                })\n              };\n            }\n            await validateTypes4({\n              value: dataPart.data,\n              schema: dataSchema,\n              context: {\n                field: `messages[${msgIdx}].parts[${partIdx}].data`,\n                entityName: dataName,\n                entityId: dataPart.id\n              }\n            });\n          }\n          if (tools && part.type.startsWith(\"tool-\")) {\n            const toolPart = part;\n            const toolName = toolPart.type.slice(5);\n            const tool2 = tools[toolName];\n            if (!tool2 && (toolPart.state === \"output-available\" || toolPart.state === \"output-error\" || toolPart.state === \"output-denied\")) {\n              continue;\n            }\n            if (!tool2) {\n              return {\n                success: false,\n                error: new TypeValidationError3({\n                  value: toolPart.input,\n                  cause: `No tool schema found for tool part ${toolName}`,\n                  context: {\n                    field: `messages[${msgIdx}].parts[${partIdx}].input`,\n                    entityName: toolName,\n                    entityId: toolPart.toolCallId\n                  }\n                })\n              };\n            }\n            if (toolPart.state === \"input-available\" || toolPart.state === \"output-available\") {\n              await validateTypes4({\n                value: toolPart.input,\n                schema: tool2.inputSchema,\n                context: {\n                  field: `messages[${msgIdx}].parts[${partIdx}].input`,\n                  entityName: toolName,\n                  entityId: toolPart.toolCallId\n                }\n              });\n            }\n            if (toolPart.state === \"output-available\" && tool2.outputSchema) {\n              await validateTypes4({\n                value: toolPart.output,\n                schema: tool2.outputSchema,\n                context: {\n                  field: `messages[${msgIdx}].parts[${partIdx}].output`,\n                  entityName: toolName,\n                  entityId: toolPart.toolCallId\n                }\n              });\n            }\n          }\n        }\n      }\n    }\n    return {\n      success: true,\n      data: validatedMessages\n    };\n  } catch (error) {\n    const err = error;\n    return {\n      success: false,\n      error: err\n    };\n  }\n}\nasync function validateUIMessages({\n  messages,\n  metadataSchema,\n  dataSchemas,\n  tools\n}) {\n  const response = await safeValidateUIMessages({\n    messages,\n    metadataSchema,\n    dataSchemas,\n    tools\n  });\n  if (!response.success)\n    throw response.error;\n  return response.data;\n}\n\n// src/agent/create-agent-ui-stream.ts\nasync function createAgentUIStream({\n  agent,\n  uiMessages,\n  options,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  experimental_transform,\n  onStepEnd,\n  onStepFinish,\n  ...uiMessageStreamOptions\n}) {\n  var _a22;\n  const validatedMessages = await validateUIMessages({\n    messages: uiMessages,\n    // tools are compatible; the casting is required because the context param is\n    // not available in ui messages\n    tools: agent.tools\n  });\n  const modelMessages = await convertToModelMessages(validatedMessages, {\n    tools: agent.tools\n  });\n  const result = await agent.stream({\n    prompt: modelMessages,\n    options,\n    abortSignal,\n    timeout,\n    experimental_sandbox: sandbox,\n    experimental_transform,\n    onStepEnd: onStepEnd != null ? onStepEnd : onStepFinish\n  });\n  const originalMessages = (_a22 = uiMessageStreamOptions.originalMessages) != null ? _a22 : validatedMessages;\n  return createAsyncIterableStream(\n    toUIMessageStream({\n      ...uiMessageStreamOptions,\n      originalMessages,\n      stream: result.stream,\n      tools: agent.tools\n    })\n  );\n}\n\n// src/agent/create-agent-ui-stream-response.ts\nasync function createAgentUIStreamResponse({\n  headers,\n  status,\n  statusText,\n  consumeSseStream,\n  ...options\n}) {\n  return createUIMessageStreamResponse({\n    headers,\n    status,\n    statusText,\n    consumeSseStream,\n    stream: await createAgentUIStream(options)\n  });\n}\n\n// src/agent/pipe-agent-ui-stream-to-response.ts\nasync function pipeAgentUIStreamToResponse({\n  response,\n  headers,\n  status,\n  statusText,\n  consumeSseStream,\n  ...options\n}) {\n  pipeUIMessageStreamToResponse({\n    response,\n    headers,\n    status,\n    statusText,\n    consumeSseStream,\n    stream: await createAgentUIStream(options)\n  });\n}\n\n// src/embed/embed.ts\nimport {\n  createIdGenerator as createIdGenerator4,\n  withUserAgentSuffix as withUserAgentSuffix4\n} from \"@ai-sdk/provider-utils\";\nvar originalGenerateCallId4 = createIdGenerator4({\n  prefix: \"call\",\n  size: 24\n});\nasync function embed({\n  model: modelArg,\n  value,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  onStart,\n  experimental_onStart,\n  onEnd,\n  experimental_onEnd,\n  _internal: { generateCallId = originalGenerateCallId4 } = {}\n}) {\n  var _a22;\n  const model = resolveEmbeddingModel(modelArg);\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const resolvedOnStart = onStart != null ? onStart : experimental_onStart;\n  const resolvedOnEnd = onEnd != null ? onEnd : experimental_onEnd;\n  const headersWithUserAgent = withUserAgentSuffix4(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const callId = generateCallId();\n  const telemetryDispatcher = createTelemetryDispatcher({\n    telemetry\n  });\n  const runInTracingChannelSpan = (_a22 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a22 : async ({ execute }) => await execute();\n  const startEvent = {\n    callId,\n    operationId: \"ai.embed\",\n    provider: model.provider,\n    modelId: model.modelId,\n    value,\n    maxRetries,\n    headers: headersWithUserAgent,\n    providerOptions\n  };\n  return await runInTracingChannelSpan({\n    type: \"embed\",\n    event: startEvent,\n    execute: async () => {\n      var _a23;\n      await notify({\n        event: startEvent,\n        callbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n      });\n      try {\n        const { embedding, usage, warnings, response, providerMetadata } = await retry(async () => {\n          var _a24, _b;\n          const embedCallId = generateCallId();\n          await notify({\n            event: {\n              callId,\n              embedCallId,\n              operationId: \"ai.embed.doEmbed\",\n              provider: model.provider,\n              modelId: model.modelId,\n              values: [value]\n            },\n            callbacks: [telemetryDispatcher.onEmbedStart]\n          });\n          const modelResponse = await model.doEmbed({\n            values: [value],\n            abortSignal,\n            headers: headersWithUserAgent,\n            providerOptions\n          });\n          const embedding2 = modelResponse.embeddings[0];\n          const usage2 = (_a24 = modelResponse.usage) != null ? _a24 : { tokens: NaN };\n          await notify({\n            event: {\n              callId,\n              embedCallId,\n              operationId: \"ai.embed.doEmbed\",\n              provider: model.provider,\n              modelId: model.modelId,\n              values: [value],\n              embeddings: modelResponse.embeddings,\n              usage: usage2\n            },\n            callbacks: [telemetryDispatcher.onEmbedEnd]\n          });\n          return {\n            embedding: embedding2,\n            usage: usage2,\n            warnings: (_b = modelResponse.warnings) != null ? _b : [],\n            providerMetadata: modelResponse.providerMetadata,\n            response: modelResponse.response\n          };\n        });\n        logWarnings({\n          warnings,\n          provider: model.provider,\n          model: model.modelId\n        });\n        await notify({\n          event: {\n            callId,\n            operationId: \"ai.embed\",\n            provider: model.provider,\n            modelId: model.modelId,\n            value,\n            embedding,\n            usage,\n            warnings,\n            providerMetadata,\n            response\n          },\n          callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n        });\n        return new DefaultEmbedResult({\n          value,\n          embedding,\n          usage,\n          warnings,\n          providerMetadata,\n          response\n        });\n      } catch (error) {\n        await ((_a23 = telemetryDispatcher.onError) == null ? void 0 : _a23.call(telemetryDispatcher, { callId, error }));\n        throw error;\n      }\n    }\n  });\n}\nvar DefaultEmbedResult = class {\n  constructor(options) {\n    this.value = options.value;\n    this.embedding = options.embedding;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.response = options.response;\n  }\n};\n\n// src/embed/embed-many.ts\nimport {\n  createIdGenerator as createIdGenerator5,\n  withUserAgentSuffix as withUserAgentSuffix5\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/split-array.ts\nfunction splitArray(array2, chunkSize) {\n  if (chunkSize <= 0) {\n    throw new Error(\"chunkSize must be greater than 0\");\n  }\n  const result = [];\n  for (let i = 0; i < array2.length; i += chunkSize) {\n    result.push(array2.slice(i, i + chunkSize));\n  }\n  return result;\n}\n\n// src/embed/embed-many.ts\nvar originalGenerateCallId5 = createIdGenerator5({\n  prefix: \"call\",\n  size: 24\n});\nasync function embedMany({\n  model: modelArg,\n  values,\n  maxParallelCalls = Infinity,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  providerOptions,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  onStart,\n  experimental_onStart,\n  onEnd,\n  experimental_onEnd,\n  _internal: { generateCallId = originalGenerateCallId5 } = {}\n}) {\n  var _a22, _b;\n  const model = resolveEmbeddingModel(modelArg);\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const resolvedOnStart = onStart != null ? onStart : experimental_onStart;\n  const resolvedOnEnd = onEnd != null ? onEnd : experimental_onEnd;\n  const headersWithUserAgent = withUserAgentSuffix5(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const callId = generateCallId();\n  const telemetryDispatcher = createTelemetryDispatcher({\n    telemetry\n  });\n  await notify({\n    event: {\n      callId,\n      operationId: \"ai.embedMany\",\n      provider: model.provider,\n      modelId: model.modelId,\n      value: values,\n      maxRetries,\n      headers: headersWithUserAgent,\n      providerOptions\n    },\n    callbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n  });\n  try {\n    const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([\n      model.maxEmbeddingsPerCall,\n      model.supportsParallelCalls\n    ]);\n    if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {\n      const { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(async () => {\n        var _a23, _b2;\n        const embedCallId = generateCallId();\n        await notify({\n          event: {\n            callId,\n            embedCallId,\n            operationId: \"ai.embedMany.doEmbed\",\n            provider: model.provider,\n            modelId: model.modelId,\n            values\n          },\n          callbacks: [telemetryDispatcher.onEmbedStart]\n        });\n        const modelResponse = await model.doEmbed({\n          values,\n          abortSignal,\n          headers: headersWithUserAgent,\n          providerOptions\n        });\n        const embeddings3 = modelResponse.embeddings;\n        const usage2 = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };\n        await notify({\n          event: {\n            callId,\n            embedCallId,\n            operationId: \"ai.embedMany.doEmbed\",\n            provider: model.provider,\n            modelId: model.modelId,\n            values,\n            embeddings: embeddings3,\n            usage: usage2\n          },\n          callbacks: [telemetryDispatcher.onEmbedEnd]\n        });\n        return {\n          embeddings: embeddings3,\n          usage: usage2,\n          warnings: (_b2 = modelResponse.warnings) != null ? _b2 : [],\n          providerMetadata: modelResponse.providerMetadata,\n          response: modelResponse.response\n        };\n      });\n      logWarnings({\n        warnings: warnings2,\n        provider: model.provider,\n        model: model.modelId\n      });\n      await notify({\n        event: {\n          callId,\n          operationId: \"ai.embedMany\",\n          provider: model.provider,\n          modelId: model.modelId,\n          value: values,\n          embedding: embeddings2,\n          usage,\n          warnings: warnings2,\n          providerMetadata: providerMetadata2,\n          response: [response]\n        },\n        callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n      });\n      return new DefaultEmbedManyResult({\n        values,\n        embeddings: embeddings2,\n        usage,\n        warnings: warnings2,\n        providerMetadata: providerMetadata2,\n        responses: [response]\n      });\n    }\n    const valueChunks = splitArray(values, maxEmbeddingsPerCall);\n    const embeddings = [];\n    const warnings = [];\n    const responses = [];\n    let tokens = 0;\n    let providerMetadata;\n    const parallelChunks = splitArray(\n      valueChunks,\n      supportsParallelCalls ? maxParallelCalls : 1\n    );\n    for (const parallelChunk of parallelChunks) {\n      const results = await Promise.all(\n        parallelChunk.map((chunk) => {\n          return retry(async () => {\n            var _a23, _b2;\n            const embedCallId = generateCallId();\n            await notify({\n              event: {\n                callId,\n                embedCallId,\n                operationId: \"ai.embedMany.doEmbed\",\n                provider: model.provider,\n                modelId: model.modelId,\n                values: chunk\n              },\n              callbacks: [telemetryDispatcher.onEmbedStart]\n            });\n            const modelResponse = await model.doEmbed({\n              values: chunk,\n              abortSignal,\n              headers: headersWithUserAgent,\n              providerOptions\n            });\n            const chunkEmbeddings = modelResponse.embeddings;\n            const usage = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };\n            await notify({\n              event: {\n                callId,\n                embedCallId,\n                operationId: \"ai.embedMany.doEmbed\",\n                provider: model.provider,\n                modelId: model.modelId,\n                values: chunk,\n                embeddings: chunkEmbeddings,\n                usage\n              },\n              callbacks: [telemetryDispatcher.onEmbedEnd]\n            });\n            return {\n              embeddings: chunkEmbeddings,\n              usage,\n              warnings: (_b2 = modelResponse.warnings) != null ? _b2 : [],\n              providerMetadata: modelResponse.providerMetadata,\n              response: modelResponse.response\n            };\n          });\n        })\n      );\n      for (const result of results) {\n        embeddings.push(...result.embeddings);\n        warnings.push(...result.warnings);\n        responses.push(result.response);\n        tokens += result.usage.tokens;\n        if (result.providerMetadata) {\n          if (!providerMetadata) {\n            providerMetadata = { ...result.providerMetadata };\n          } else {\n            for (const [providerName, metadata] of Object.entries(\n              result.providerMetadata\n            )) {\n              providerMetadata[providerName] = {\n                ...(_a22 = providerMetadata[providerName]) != null ? _a22 : {},\n                ...metadata\n              };\n            }\n          }\n        }\n      }\n    }\n    logWarnings({\n      warnings,\n      provider: model.provider,\n      model: model.modelId\n    });\n    await notify({\n      event: {\n        callId,\n        operationId: \"ai.embedMany\",\n        provider: model.provider,\n        modelId: model.modelId,\n        value: values,\n        embedding: embeddings,\n        usage: { tokens },\n        warnings,\n        providerMetadata,\n        response: responses\n      },\n      callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n    });\n    return new DefaultEmbedManyResult({\n      values,\n      embeddings,\n      usage: { tokens },\n      warnings,\n      providerMetadata,\n      responses\n    });\n  } catch (error) {\n    await ((_b = telemetryDispatcher.onError) == null ? void 0 : _b.call(telemetryDispatcher, { callId, error }));\n    throw error;\n  }\n}\nvar DefaultEmbedManyResult = class {\n  constructor(options) {\n    this.values = options.values;\n    this.embeddings = options.embeddings;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.responses = options.responses;\n  }\n};\n\n// src/generate-image/generate-image.ts\nimport {\n  convertBase64ToUint8Array as convertBase64ToUint8Array4,\n  detectMediaType as detectMediaType2,\n  withUserAgentSuffix as withUserAgentSuffix6\n} from \"@ai-sdk/provider-utils\";\n\n// src/prompt/data-content.ts\nimport {\n  convertBase64ToUint8Array as convertBase64ToUint8Array3,\n  convertUint8ArrayToBase64 as convertUint8ArrayToBase643\n} from \"@ai-sdk/provider-utils\";\nfunction convertDataContentToBase64String(content) {\n  if (typeof content === \"string\") {\n    return content;\n  }\n  if (content instanceof ArrayBuffer) {\n    return convertUint8ArrayToBase643(new Uint8Array(content));\n  }\n  return convertUint8ArrayToBase643(content);\n}\nfunction convertDataContentToUint8Array(content) {\n  if (content instanceof Uint8Array) {\n    return content;\n  }\n  if (typeof content === \"string\") {\n    try {\n      return convertBase64ToUint8Array3(content);\n    } catch (error) {\n      throw new InvalidDataContentError({\n        message: \"Invalid data content. Content string is not a base64-encoded media.\",\n        content,\n        cause: error\n      });\n    }\n  }\n  if (content instanceof ArrayBuffer) {\n    return new Uint8Array(content);\n  }\n  throw new InvalidDataContentError({ content });\n}\n\n// src/generate-image/generate-image.ts\nasync function generateImage({\n  model: modelArg,\n  prompt: promptArg,\n  n = 1,\n  maxImagesPerCall,\n  size,\n  aspectRatio,\n  seed,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers\n}) {\n  var _a22, _b;\n  const model = resolveImageModel(modelArg);\n  const headersWithUserAgent = withUserAgentSuffix6(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const maxImagesPerCallWithDefault = (_a22 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a22 : 1;\n  const callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n  const callImageCounts = Array.from({ length: callCount }, (_, i) => {\n    if (i < callCount - 1) {\n      return maxImagesPerCallWithDefault;\n    }\n    const remainder = n % maxImagesPerCallWithDefault;\n    return remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n  });\n  const results = await Promise.all(\n    callImageCounts.map(\n      async (callImageCount) => await retry(() => {\n        const { prompt, files, mask } = normalizePrompt(promptArg);\n        return model.doGenerate({\n          prompt,\n          files,\n          mask,\n          n: callImageCount,\n          abortSignal,\n          headers: headersWithUserAgent,\n          size,\n          aspectRatio,\n          seed,\n          providerOptions: providerOptions != null ? providerOptions : {}\n        });\n      })\n    )\n  );\n  const images = [];\n  const warnings = [];\n  const responses = [];\n  const providerMetadata = {};\n  let totalUsage = {\n    inputTokens: void 0,\n    outputTokens: void 0,\n    totalTokens: void 0\n  };\n  for (const result of results) {\n    images.push(\n      ...result.images.map(\n        (image) => {\n          var _a23;\n          return new DefaultGeneratedFile({\n            data: image,\n            mediaType: (_a23 = detectMediaType2({\n              data: image,\n              topLevelType: \"image\"\n            })) != null ? _a23 : \"image/png\"\n          });\n        }\n      )\n    );\n    warnings.push(...result.warnings);\n    if (result.usage != null) {\n      totalUsage = addImageModelUsage(totalUsage, result.usage);\n    }\n    if (result.providerMetadata) {\n      for (const [providerName, metadata] of Object.entries(result.providerMetadata)) {\n        if (providerName === \"gateway\") {\n          const currentEntry = providerMetadata[providerName];\n          if (currentEntry != null && typeof currentEntry === \"object\") {\n            providerMetadata[providerName] = {\n              ...currentEntry,\n              ...metadata\n            };\n          } else {\n            providerMetadata[providerName] = metadata;\n          }\n          const imagesValue = providerMetadata[providerName].images;\n          if (Array.isArray(imagesValue) && imagesValue.length === 0) {\n            delete providerMetadata[providerName].images;\n          }\n        } else {\n          (_b = providerMetadata[providerName]) != null ? _b : providerMetadata[providerName] = { images: [] };\n          providerMetadata[providerName].images.push(\n            ...result.providerMetadata[providerName].images\n          );\n        }\n      }\n    }\n    responses.push(result.response);\n  }\n  logWarnings({ warnings, provider: model.provider, model: model.modelId });\n  if (!images.length) {\n    throw new NoImageGeneratedError({ responses });\n  }\n  return new DefaultGenerateImageResult({\n    images,\n    warnings,\n    responses,\n    providerMetadata,\n    usage: totalUsage\n  });\n}\nvar DefaultGenerateImageResult = class {\n  constructor(options) {\n    this.images = options.images;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = options.providerMetadata;\n    this.usage = options.usage;\n  }\n  get image() {\n    return this.images[0];\n  }\n};\nasync function invokeModelMaxImagesPerCall(model) {\n  const isFunction = model.maxImagesPerCall instanceof Function;\n  if (!isFunction) {\n    return model.maxImagesPerCall;\n  }\n  return model.maxImagesPerCall({\n    modelId: model.modelId\n  });\n}\nfunction normalizePrompt(prompt) {\n  if (typeof prompt === \"string\") {\n    return { prompt, files: void 0, mask: void 0 };\n  }\n  return {\n    prompt: prompt.text,\n    files: prompt.images.map(toImageModelV4File),\n    mask: prompt.mask ? toImageModelV4File(prompt.mask) : void 0\n  };\n}\nfunction toImageModelV4File(dataContent) {\n  if (typeof dataContent === \"string\" && dataContent.startsWith(\"http\")) {\n    return {\n      type: \"url\",\n      url: dataContent\n    };\n  }\n  if (typeof dataContent === \"string\" && dataContent.startsWith(\"data:\")) {\n    const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(dataContent);\n    if (base64Content != null) {\n      const uint8Data2 = convertBase64ToUint8Array4(base64Content);\n      return {\n        type: \"file\",\n        data: uint8Data2,\n        mediaType: dataUrlMediaType || detectMediaType2({\n          data: uint8Data2,\n          topLevelType: \"image\"\n        }) || \"image/png\"\n      };\n    }\n  }\n  const uint8Data = convertDataContentToUint8Array(dataContent);\n  return {\n    type: \"file\",\n    data: uint8Data,\n    mediaType: detectMediaType2({\n      data: uint8Data,\n      topLevelType: \"image\"\n    }) || \"image/png\"\n  };\n}\n\n// src/generate-object/generate-object.ts\nimport {\n  createIdGenerator as createIdGenerator6,\n  withUserAgentSuffix as withUserAgentSuffix7\n} from \"@ai-sdk/provider-utils\";\n\n// src/generate-text/extract-reasoning-content.ts\nfunction extractReasoningContent(content) {\n  const parts = content.filter(\n    (content2) => content2.type === \"reasoning\"\n  );\n  return parts.length === 0 ? void 0 : parts.map((content2) => content2.text).join(\"\\n\");\n}\n\n// src/generate-text/extract-text-content.ts\nfunction extractTextContent(content) {\n  const parts = content.filter(\n    (content2) => content2.type === \"text\"\n  );\n  if (parts.length === 0) {\n    return void 0;\n  }\n  return parts.map((content2) => content2.text).join(\"\");\n}\n\n// src/generate-object/output-strategy.ts\nimport {\n  isJSONArray,\n  isJSONObject,\n  TypeValidationError as TypeValidationError4,\n  UnsupportedFunctionalityError as UnsupportedFunctionalityError3\n} from \"@ai-sdk/provider\";\nimport {\n  asSchema as asSchema5,\n  safeValidateTypes as safeValidateTypes5\n} from \"@ai-sdk/provider-utils\";\nvar noSchemaOutputStrategy = {\n  type: \"no-schema\",\n  jsonSchema: async () => void 0,\n  async validatePartialResult({ value, textDelta }) {\n    return { success: true, value: { partial: value, textDelta } };\n  },\n  async validateFinalResult(value, context) {\n    return value === void 0 ? {\n      success: false,\n      error: new NoObjectGeneratedError({\n        message: \"No object generated: response did not match schema.\",\n        text: context.text,\n        response: context.response,\n        usage: context.usage,\n        finishReason: context.finishReason\n      })\n    } : { success: true, value };\n  },\n  createElementStream() {\n    throw new UnsupportedFunctionalityError3({\n      functionality: \"element streams in no-schema mode\"\n    });\n  }\n};\nvar objectOutputStrategy = (schema) => ({\n  type: \"object\",\n  jsonSchema: async () => await schema.jsonSchema,\n  async validatePartialResult({ value, textDelta }) {\n    return {\n      success: true,\n      value: {\n        // Note: currently no validation of partial results:\n        partial: value,\n        textDelta\n      }\n    };\n  },\n  async validateFinalResult(value) {\n    return safeValidateTypes5({ value, schema });\n  },\n  createElementStream() {\n    throw new UnsupportedFunctionalityError3({\n      functionality: \"element streams in object mode\"\n    });\n  }\n});\nvar arrayOutputStrategy = (schema) => {\n  return {\n    type: \"array\",\n    // wrap in object that contains array of elements, since most LLMs will not\n    // be able to generate an array directly:\n    // possible future optimization: use arrays directly when model supports grammar-guided generation\n    jsonSchema: async () => {\n      const { $schema: _$schema, ...itemSchema } = await schema.jsonSchema;\n      return {\n        $schema: \"http://json-schema.org/draft-07/schema#\",\n        type: \"object\",\n        properties: {\n          elements: { type: \"array\", items: itemSchema }\n        },\n        required: [\"elements\"],\n        additionalProperties: false\n      };\n    },\n    async validatePartialResult({\n      value,\n      latestObject,\n      isFirstDelta,\n      isFinalDelta\n    }) {\n      var _a22;\n      if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n        return {\n          success: false,\n          error: new TypeValidationError4({\n            value,\n            cause: \"value must be an object that contains an array of elements\"\n          })\n        };\n      }\n      const inputArray = value.elements;\n      const resultArray = [];\n      for (let i = 0; i < inputArray.length; i++) {\n        const element = inputArray[i];\n        const result = await safeValidateTypes5({ value: element, schema });\n        if (i === inputArray.length - 1 && !isFinalDelta) {\n          continue;\n        }\n        if (!result.success) {\n          return result;\n        }\n        resultArray.push(result.value);\n      }\n      const publishedElementCount = (_a22 = latestObject == null ? void 0 : latestObject.length) != null ? _a22 : 0;\n      let textDelta = \"\";\n      if (isFirstDelta) {\n        textDelta += \"[\";\n      }\n      if (publishedElementCount > 0) {\n        textDelta += \",\";\n      }\n      textDelta += resultArray.slice(publishedElementCount).map((element) => JSON.stringify(element)).join(\",\");\n      if (isFinalDelta) {\n        textDelta += \"]\";\n      }\n      return {\n        success: true,\n        value: {\n          partial: resultArray,\n          textDelta\n        }\n      };\n    },\n    async validateFinalResult(value) {\n      if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n        return {\n          success: false,\n          error: new TypeValidationError4({\n            value,\n            cause: \"value must be an object that contains an array of elements\"\n          })\n        };\n      }\n      const inputArray = value.elements;\n      const resultArray = [];\n      for (const element of inputArray) {\n        const result = await safeValidateTypes5({ value: element, schema });\n        if (!result.success) {\n          return result;\n        }\n        resultArray.push(result.value);\n      }\n      return { success: true, value: resultArray };\n    },\n    createElementStream(originalStream) {\n      let publishedElements = 0;\n      return createAsyncIterableStream(\n        originalStream.pipeThrough(\n          new TransformStream({\n            transform(chunk, controller) {\n              switch (chunk.type) {\n                case \"object\": {\n                  const array2 = chunk.object;\n                  for (; publishedElements < array2.length; publishedElements++) {\n                    controller.enqueue(array2[publishedElements]);\n                  }\n                  break;\n                }\n                case \"text-delta\":\n                case \"finish\":\n                case \"error\":\n                  break;\n                default: {\n                  const _exhaustiveCheck = chunk;\n                  throw new Error(\n                    `Unsupported chunk type: ${_exhaustiveCheck}`\n                  );\n                }\n              }\n            }\n          })\n        )\n      );\n    }\n  };\n};\nvar enumOutputStrategy = (enumValues) => {\n  return {\n    type: \"enum\",\n    // wrap in object that contains result, since most LLMs will not\n    // be able to generate an enum value directly:\n    // possible future optimization: use enums directly when model supports top-level enums\n    jsonSchema: async () => ({\n      $schema: \"http://json-schema.org/draft-07/schema#\",\n      type: \"object\",\n      properties: {\n        result: { type: \"string\", enum: enumValues }\n      },\n      required: [\"result\"],\n      additionalProperties: false\n    }),\n    async validateFinalResult(value) {\n      if (!isJSONObject(value) || typeof value.result !== \"string\") {\n        return {\n          success: false,\n          error: new TypeValidationError4({\n            value,\n            cause: 'value must be an object that contains a string in the \"result\" property.'\n          })\n        };\n      }\n      const result = value.result;\n      return enumValues.includes(result) ? { success: true, value: result } : {\n        success: false,\n        error: new TypeValidationError4({\n          value,\n          cause: \"value must be a string in the enum\"\n        })\n      };\n    },\n    async validatePartialResult({ value, textDelta }) {\n      if (!isJSONObject(value) || typeof value.result !== \"string\") {\n        return {\n          success: false,\n          error: new TypeValidationError4({\n            value,\n            cause: 'value must be an object that contains a string in the \"result\" property.'\n          })\n        };\n      }\n      const result = value.result;\n      const possibleEnumValues = enumValues.filter(\n        (enumValue) => enumValue.startsWith(result)\n      );\n      if (value.result.length === 0 || possibleEnumValues.length === 0) {\n        return {\n          success: false,\n          error: new TypeValidationError4({\n            value,\n            cause: \"value must be a string in the enum\"\n          })\n        };\n      }\n      return {\n        success: true,\n        value: {\n          partial: possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n          textDelta\n        }\n      };\n    },\n    createElementStream() {\n      throw new UnsupportedFunctionalityError3({\n        functionality: \"element streams in enum mode\"\n      });\n    }\n  };\n};\nfunction getOutputStrategy({\n  output,\n  schema,\n  enumValues\n}) {\n  switch (output) {\n    case \"object\":\n      return objectOutputStrategy(asSchema5(schema));\n    case \"array\":\n      return arrayOutputStrategy(asSchema5(schema));\n    case \"enum\":\n      return enumOutputStrategy(enumValues);\n    case \"no-schema\":\n      return noSchemaOutputStrategy;\n    default: {\n      const _exhaustiveCheck = output;\n      throw new Error(`Unsupported output: ${_exhaustiveCheck}`);\n    }\n  }\n}\n\n// src/generate-object/parse-and-validate-object-result.ts\nimport { JSONParseError as JSONParseError2, TypeValidationError as TypeValidationError5 } from \"@ai-sdk/provider\";\nimport { safeParseJSON as safeParseJSON4 } from \"@ai-sdk/provider-utils\";\nasync function parseAndValidateObjectResult(result, outputStrategy, context) {\n  const parseResult = await safeParseJSON4({ text: result });\n  if (!parseResult.success) {\n    throw new NoObjectGeneratedError({\n      message: \"No object generated: could not parse the response.\",\n      cause: parseResult.error,\n      text: result,\n      response: context.response,\n      usage: context.usage,\n      finishReason: context.finishReason\n    });\n  }\n  const validationResult = await outputStrategy.validateFinalResult(\n    parseResult.value,\n    {\n      text: result,\n      response: context.response,\n      usage: context.usage\n    }\n  );\n  if (!validationResult.success) {\n    throw new NoObjectGeneratedError({\n      message: \"No object generated: response did not match schema.\",\n      cause: validationResult.error,\n      text: result,\n      response: context.response,\n      usage: context.usage,\n      finishReason: context.finishReason\n    });\n  }\n  return validationResult.value;\n}\nasync function parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, context) {\n  try {\n    return await parseAndValidateObjectResult(result, outputStrategy, context);\n  } catch (error) {\n    if (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError2.isInstance(error.cause) || TypeValidationError5.isInstance(error.cause))) {\n      const repairedText = await repairText({\n        text: result,\n        error: error.cause\n      });\n      if (repairedText === null) {\n        throw error;\n      }\n      return await parseAndValidateObjectResult(\n        repairedText,\n        outputStrategy,\n        context\n      );\n    }\n    throw error;\n  }\n}\n\n// src/generate-object/validate-object-generation-input.ts\nfunction validateObjectGenerationInput({\n  output,\n  schema,\n  schemaName,\n  schemaDescription,\n  enumValues\n}) {\n  if (output != null && output !== \"object\" && output !== \"array\" && output !== \"enum\" && output !== \"no-schema\") {\n    throw new InvalidArgumentError({\n      parameter: \"output\",\n      value: output,\n      message: \"Invalid output type.\"\n    });\n  }\n  if (output === \"no-schema\") {\n    if (schema != null) {\n      throw new InvalidArgumentError({\n        parameter: \"schema\",\n        value: schema,\n        message: \"Schema is not supported for no-schema output.\"\n      });\n    }\n    if (schemaDescription != null) {\n      throw new InvalidArgumentError({\n        parameter: \"schemaDescription\",\n        value: schemaDescription,\n        message: \"Schema description is not supported for no-schema output.\"\n      });\n    }\n    if (schemaName != null) {\n      throw new InvalidArgumentError({\n        parameter: \"schemaName\",\n        value: schemaName,\n        message: \"Schema name is not supported for no-schema output.\"\n      });\n    }\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: \"enumValues\",\n        value: enumValues,\n        message: \"Enum values are not supported for no-schema output.\"\n      });\n    }\n  }\n  if (output === \"object\") {\n    if (schema == null) {\n      throw new InvalidArgumentError({\n        parameter: \"schema\",\n        value: schema,\n        message: \"Schema is required for object output.\"\n      });\n    }\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: \"enumValues\",\n        value: enumValues,\n        message: \"Enum values are not supported for object output.\"\n      });\n    }\n  }\n  if (output === \"array\") {\n    if (schema == null) {\n      throw new InvalidArgumentError({\n        parameter: \"schema\",\n        value: schema,\n        message: \"Element schema is required for array output.\"\n      });\n    }\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: \"enumValues\",\n        value: enumValues,\n        message: \"Enum values are not supported for array output.\"\n      });\n    }\n  }\n  if (output === \"enum\") {\n    if (schema != null) {\n      throw new InvalidArgumentError({\n        parameter: \"schema\",\n        value: schema,\n        message: \"Schema is not supported for enum output.\"\n      });\n    }\n    if (schemaDescription != null) {\n      throw new InvalidArgumentError({\n        parameter: \"schemaDescription\",\n        value: schemaDescription,\n        message: \"Schema description is not supported for enum output.\"\n      });\n    }\n    if (schemaName != null) {\n      throw new InvalidArgumentError({\n        parameter: \"schemaName\",\n        value: schemaName,\n        message: \"Schema name is not supported for enum output.\"\n      });\n    }\n    if (enumValues == null) {\n      throw new InvalidArgumentError({\n        parameter: \"enumValues\",\n        value: enumValues,\n        message: \"Enum values are required for enum output.\"\n      });\n    }\n    for (const value of enumValues) {\n      if (typeof value !== \"string\") {\n        throw new InvalidArgumentError({\n          parameter: \"enumValues\",\n          value,\n          message: \"Enum values must be strings.\"\n        });\n      }\n    }\n  }\n}\n\n// src/generate-object/generate-object.ts\nvar originalGenerateId4 = createIdGenerator6({ prefix: \"aiobj\", size: 24 });\nasync function generateObject(options) {\n  var _a22, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n  const {\n    model: modelArg,\n    output = \"object\",\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    headers,\n    experimental_repairText: repairText,\n    experimental_telemetry,\n    telemetry = experimental_telemetry,\n    experimental_download: download2,\n    providerOptions,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onStepEnd,\n    onStepFinish,\n    onFinish,\n    _internal: {\n      generateId: generateId2 = originalGenerateId4,\n      currentDate = () => /* @__PURE__ */ new Date()\n    } = {},\n    ...settings\n  } = options;\n  const model = resolveLanguageModel(modelArg);\n  const enumValues = \"enum\" in options ? options.enum : void 0;\n  const {\n    schema: inputSchema,\n    schemaDescription,\n    schemaName\n  } = \"schema\" in options ? options : {};\n  validateObjectGenerationInput({\n    output,\n    schema: inputSchema,\n    schemaName,\n    schemaDescription,\n    enumValues\n  });\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const outputStrategy = getOutputStrategy({\n    output,\n    schema: inputSchema,\n    enumValues\n  });\n  const callSettings = prepareLanguageModelCallOptions(settings);\n  const headersWithUserAgent = withUserAgentSuffix7(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const telemetryDispatcher = createTelemetryDispatcher({\n    telemetry\n  });\n  const resolvedOnStart = onStart != null ? onStart : experimental_onStart;\n  const resolvedOnStepStart = onStepStart != null ? onStepStart : experimental_onStepStart;\n  const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish;\n  const jsonSchema2 = await outputStrategy.jsonSchema();\n  const callId = generateId2();\n  await notify({\n    event: {\n      callId,\n      operationId: \"ai.generateObject\",\n      provider: model.provider,\n      modelId: model.modelId,\n      system: instructions != null ? instructions : system,\n      prompt,\n      messages,\n      maxOutputTokens: callSettings.maxOutputTokens,\n      temperature: callSettings.temperature,\n      topP: callSettings.topP,\n      topK: callSettings.topK,\n      presencePenalty: callSettings.presencePenalty,\n      frequencyPenalty: callSettings.frequencyPenalty,\n      seed: callSettings.seed,\n      maxRetries,\n      headers: headersWithUserAgent,\n      providerOptions,\n      output: outputStrategy.type,\n      schema: jsonSchema2,\n      schemaName,\n      schemaDescription\n    },\n    callbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n  });\n  try {\n    const standardizedPrompt = await standardizePrompt({\n      instructions,\n      system,\n      prompt,\n      messages,\n      allowSystemInMessages\n    });\n    const promptMessages = await convertToLanguageModelPrompt({\n      prompt: standardizedPrompt,\n      supportedUrls: await model.supportedUrls,\n      download: download2,\n      provider: model.provider.split(\".\")[0]\n    });\n    await notify({\n      event: {\n        callId,\n        stepNumber: 0,\n        provider: model.provider,\n        modelId: model.modelId,\n        providerOptions,\n        headers: headersWithUserAgent,\n        promptMessages\n      },\n      callbacks: [resolvedOnStepStart, telemetryDispatcher.onObjectStepStart]\n    });\n    const generateResult = await retry(\n      () => model.doGenerate({\n        responseFormat: {\n          type: \"json\",\n          schema: jsonSchema2,\n          name: schemaName,\n          description: schemaDescription\n        },\n        ...prepareLanguageModelCallOptions(settings),\n        prompt: promptMessages,\n        providerOptions,\n        abortSignal,\n        headers: headersWithUserAgent\n      })\n    );\n    const responseData = {\n      id: (_b = (_a22 = generateResult.response) == null ? void 0 : _a22.id) != null ? _b : generateId2(),\n      timestamp: (_d = (_c = generateResult.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),\n      modelId: (_f = (_e = generateResult.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,\n      headers: (_g = generateResult.response) == null ? void 0 : _g.headers,\n      body: (_h = generateResult.response) == null ? void 0 : _h.body\n    };\n    const text2 = extractTextContent(generateResult.content);\n    const reasoning = extractReasoningContent(generateResult.content);\n    if (text2 === void 0) {\n      throw new NoObjectGeneratedError({\n        message: \"No object generated: the model did not return a response.\",\n        response: responseData,\n        usage: asLanguageModelUsage(generateResult.usage),\n        finishReason: generateResult.finishReason.unified\n      });\n    }\n    const finishReason = generateResult.finishReason.unified;\n    const usage = asLanguageModelUsage(generateResult.usage);\n    const warnings = generateResult.warnings;\n    const resultProviderMetadata = generateResult.providerMetadata;\n    const request = (_i = generateResult.request) != null ? _i : {};\n    const response = responseData;\n    logWarnings({\n      warnings,\n      provider: model.provider,\n      model: model.modelId\n    });\n    const stepFinishEvent = {\n      callId,\n      stepNumber: 0,\n      provider: model.provider,\n      modelId: model.modelId,\n      finishReason,\n      usage,\n      objectText: text2,\n      msToFirstChunk: void 0,\n      reasoning,\n      warnings,\n      request,\n      response,\n      providerMetadata: resultProviderMetadata\n    };\n    await notify({\n      event: stepFinishEvent,\n      callbacks: [resolvedOnStepEnd, telemetryDispatcher.onObjectStepEnd]\n    });\n    const object2 = await parseAndValidateObjectResultWithRepair(\n      text2,\n      outputStrategy,\n      repairText,\n      {\n        response,\n        usage,\n        finishReason\n      }\n    );\n    await notify({\n      event: {\n        callId,\n        object: object2,\n        error: void 0,\n        reasoning,\n        finishReason,\n        usage,\n        warnings,\n        request,\n        response,\n        providerMetadata: resultProviderMetadata\n      },\n      callbacks: [onFinish, telemetryDispatcher.onEnd]\n    });\n    return new DefaultGenerateObjectResult({\n      object: object2,\n      reasoning,\n      finishReason,\n      usage,\n      warnings,\n      request,\n      response,\n      providerMetadata: resultProviderMetadata\n    });\n  } catch (error) {\n    await ((_j = telemetryDispatcher.onError) == null ? void 0 : _j.call(telemetryDispatcher, { callId, error }));\n    throw wrapGatewayError(error);\n  }\n}\nvar DefaultGenerateObjectResult = class {\n  constructor(options) {\n    this.object = options.object;\n    this.finishReason = options.finishReason;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.response = options.response;\n    this.request = options.request;\n    this.reasoning = options.reasoning;\n  }\n  toJsonResponse(init) {\n    var _a22;\n    return new Response(JSON.stringify(this.object), {\n      status: (_a22 = init == null ? void 0 : init.status) != null ? _a22 : 200,\n      headers: prepareHeaders(init == null ? void 0 : init.headers, {\n        \"content-type\": \"application/json; charset=utf-8\"\n      })\n    });\n  }\n};\n\n// src/generate-object/stream-object.ts\nimport {\n  createIdGenerator as createIdGenerator7,\n  DelayedPromise as DelayedPromise2\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/cosine-similarity.ts\nfunction cosineSimilarity(vector1, vector2) {\n  if (vector1.length !== vector2.length) {\n    throw new InvalidArgumentError({\n      parameter: \"vector1,vector2\",\n      value: { vector1Length: vector1.length, vector2Length: vector2.length },\n      message: `Vectors must have the same length`\n    });\n  }\n  const n = vector1.length;\n  if (n === 0) {\n    return 0;\n  }\n  let magnitudeSquared1 = 0;\n  let magnitudeSquared2 = 0;\n  let dotProduct = 0;\n  for (let i = 0; i < n; i++) {\n    const value1 = vector1[i];\n    const value2 = vector2[i];\n    magnitudeSquared1 += value1 * value1;\n    magnitudeSquared2 += value2 * value2;\n    dotProduct += value1 * value2;\n  }\n  return magnitudeSquared1 === 0 || magnitudeSquared2 === 0 ? 0 : dotProduct / (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\n\n// src/util/download/create-download.ts\nfunction createDownload(options) {\n  return ({ url, abortSignal }) => download({ url, maxBytes: options == null ? void 0 : options.maxBytes, abortSignal });\n}\n\n// src/util/data-url.ts\nfunction getTextFromDataUrl(dataUrl) {\n  const [header, base64Content] = dataUrl.split(\",\");\n  const mediaType = header.split(\";\")[0].split(\":\")[1];\n  if (mediaType == null || base64Content == null) {\n    throw new Error(\"Invalid data URL format\");\n  }\n  try {\n    return window.atob(base64Content);\n  } catch (e) {\n    throw new Error(`Error decoding data URL`);\n  }\n}\n\n// src/util/is-deep-equal-data.ts\nfunction isDeepEqualData(obj1, obj2) {\n  if (obj1 === obj2)\n    return true;\n  if (obj1 == null || obj2 == null)\n    return false;\n  if (typeof obj1 !== \"object\" && typeof obj2 !== \"object\")\n    return obj1 === obj2;\n  if (obj1.constructor !== obj2.constructor)\n    return false;\n  if (obj1 instanceof Date && obj2 instanceof Date) {\n    return obj1.getTime() === obj2.getTime();\n  }\n  if (Array.isArray(obj1)) {\n    if (obj1.length !== obj2.length)\n      return false;\n    for (let i = 0; i < obj1.length; i++) {\n      if (!isDeepEqualData(obj1[i], obj2[i]))\n        return false;\n    }\n    return true;\n  }\n  const keys1 = Object.keys(obj1);\n  const keys2 = Object.keys(obj2);\n  if (keys1.length !== keys2.length)\n    return false;\n  for (const key of keys1) {\n    if (!keys2.includes(key))\n      return false;\n    if (!isDeepEqualData(obj1[key], obj2[key]))\n      return false;\n  }\n  return true;\n}\n\n// src/util/serial-job-executor.ts\nvar SerialJobExecutor = class {\n  constructor() {\n    this.queue = [];\n    this.isProcessing = false;\n  }\n  async processQueue() {\n    if (this.isProcessing) {\n      return;\n    }\n    this.isProcessing = true;\n    while (this.queue.length > 0) {\n      await this.queue[0]();\n      this.queue.shift();\n    }\n    this.isProcessing = false;\n  }\n  async run(job) {\n    return new Promise((resolve3, reject) => {\n      this.queue.push(async () => {\n        try {\n          await job();\n          resolve3();\n        } catch (error) {\n          reject(error);\n        }\n      });\n      void this.processQueue();\n    });\n  }\n};\n\n// src/util/simulate-readable-stream.ts\nimport { delay as delayFunction } from \"@ai-sdk/provider-utils\";\nfunction simulateReadableStream({\n  chunks,\n  initialDelayInMs = 0,\n  chunkDelayInMs = 0,\n  _internal\n}) {\n  var _a22;\n  const delay2 = (_a22 = _internal == null ? void 0 : _internal.delay) != null ? _a22 : delayFunction;\n  let index = 0;\n  return new ReadableStream({\n    async pull(controller) {\n      if (index < chunks.length) {\n        await delay2(index === 0 ? initialDelayInMs : chunkDelayInMs);\n        controller.enqueue(chunks[index++]);\n      } else {\n        controller.close();\n      }\n    }\n  });\n}\n\n// src/generate-object/stream-object.ts\nvar originalGenerateId5 = createIdGenerator7({ prefix: \"aiobj\", size: 24 });\nfunction streamObject(options) {\n  const {\n    model,\n    output = \"object\",\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    maxRetries,\n    abortSignal,\n    headers,\n    experimental_repairText: repairText,\n    experimental_telemetry,\n    telemetry = experimental_telemetry,\n    experimental_download: download2,\n    providerOptions,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onStepEnd,\n    onStepFinish,\n    onError = ({ error }) => {\n      console.error(error);\n    },\n    onFinish,\n    _internal: {\n      generateId: generateId2 = originalGenerateId5,\n      currentDate = () => /* @__PURE__ */ new Date(),\n      now: now2 = now\n    } = {},\n    ...settings\n  } = options;\n  const enumValues = \"enum\" in options && options.enum ? options.enum : void 0;\n  const {\n    schema: inputSchema,\n    schemaDescription,\n    schemaName\n  } = \"schema\" in options ? options : {};\n  validateObjectGenerationInput({\n    output,\n    schema: inputSchema,\n    schemaName,\n    schemaDescription,\n    enumValues\n  });\n  const outputStrategy = getOutputStrategy({\n    output,\n    schema: inputSchema,\n    enumValues\n  });\n  return new DefaultStreamObjectResult({\n    model,\n    telemetry,\n    headers,\n    settings,\n    maxRetries,\n    abortSignal,\n    outputStrategy,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    schemaName,\n    schemaDescription,\n    providerOptions,\n    repairText,\n    onStart: onStart != null ? onStart : experimental_onStart,\n    onStepStart: onStepStart != null ? onStepStart : experimental_onStepStart,\n    onStepFinish: onStepEnd != null ? onStepEnd : onStepFinish,\n    onError,\n    onFinish,\n    download: download2,\n    generateId: generateId2,\n    currentDate,\n    now: now2\n  });\n}\nvar DefaultStreamObjectResult = class {\n  constructor({\n    model: modelArg,\n    headers,\n    telemetry,\n    settings,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    outputStrategy,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    schemaName,\n    schemaDescription,\n    providerOptions,\n    repairText,\n    onStart,\n    onStepStart,\n    onStepFinish,\n    onError,\n    onFinish,\n    download: download2,\n    generateId: generateId2,\n    currentDate,\n    now: now2\n  }) {\n    this._object = new DelayedPromise2();\n    this._usage = new DelayedPromise2();\n    this._providerMetadata = new DelayedPromise2();\n    this._warnings = new DelayedPromise2();\n    this._request = new DelayedPromise2();\n    this._response = new DelayedPromise2();\n    this._finishReason = new DelayedPromise2();\n    const model = resolveLanguageModel(modelArg);\n    const { maxRetries, retry } = prepareRetries({\n      maxRetries: maxRetriesArg,\n      abortSignal\n    });\n    const callSettings = prepareLanguageModelCallOptions(settings);\n    const telemetryDispatcher = createTelemetryDispatcher({\n      telemetry\n    });\n    const self = this;\n    const stitchableStream = createStitchableStream();\n    const eventProcessor = new TransformStream({\n      transform(chunk, controller) {\n        controller.enqueue(chunk);\n        if (chunk.type === \"error\") {\n          onError({ error: wrapGatewayError(chunk.error) });\n        }\n      }\n    });\n    this.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n    const callId = generateId2();\n    (async () => {\n      const jsonSchema2 = await outputStrategy.jsonSchema();\n      await notify({\n        event: {\n          callId,\n          operationId: \"ai.streamObject\",\n          provider: model.provider,\n          modelId: model.modelId,\n          system: instructions != null ? instructions : system,\n          prompt,\n          messages,\n          maxOutputTokens: callSettings.maxOutputTokens,\n          temperature: callSettings.temperature,\n          topP: callSettings.topP,\n          topK: callSettings.topK,\n          presencePenalty: callSettings.presencePenalty,\n          frequencyPenalty: callSettings.frequencyPenalty,\n          seed: callSettings.seed,\n          maxRetries,\n          headers,\n          providerOptions,\n          output: outputStrategy.type,\n          schema: jsonSchema2,\n          schemaName,\n          schemaDescription\n        },\n        callbacks: [onStart, telemetryDispatcher.onStart]\n      });\n      const standardizedPrompt = await standardizePrompt({\n        instructions,\n        system,\n        prompt,\n        messages,\n        allowSystemInMessages\n      });\n      const callOptions = {\n        responseFormat: {\n          type: \"json\",\n          schema: jsonSchema2,\n          name: schemaName,\n          description: schemaDescription\n        },\n        ...prepareLanguageModelCallOptions(settings),\n        prompt: await convertToLanguageModelPrompt({\n          prompt: standardizedPrompt,\n          supportedUrls: await model.supportedUrls,\n          download: download2,\n          provider: model.provider.split(\".\")[0]\n        }),\n        providerOptions,\n        abortSignal,\n        headers,\n        includeRawChunks: false\n      };\n      await notify({\n        event: {\n          callId,\n          stepNumber: 0,\n          provider: model.provider,\n          modelId: model.modelId,\n          providerOptions,\n          headers,\n          promptMessages: callOptions.prompt\n        },\n        callbacks: [onStepStart, telemetryDispatcher.onObjectStepStart]\n      });\n      const transformer = {\n        transform: (chunk, controller) => {\n          switch (chunk.type) {\n            case \"text-delta\":\n              controller.enqueue(chunk.delta);\n              break;\n            case \"response-metadata\":\n            case \"finish\":\n            case \"error\":\n            case \"stream-start\":\n              controller.enqueue(chunk);\n              break;\n          }\n        }\n      };\n      const startTimestampMs = now2();\n      const { stream, response, request } = await retry(\n        () => model.doStream(callOptions)\n      );\n      self._request.resolve(request != null ? request : {});\n      let warnings;\n      let usage = createNullLanguageModelUsage();\n      let finishReason;\n      let providerMetadata;\n      let object2;\n      let error;\n      let msToFirstChunk = void 0;\n      let accumulatedText = \"\";\n      let textDelta = \"\";\n      let fullResponse = {\n        id: generateId2(),\n        timestamp: currentDate(),\n        modelId: model.modelId\n      };\n      let latestObjectJson = void 0;\n      let latestObject = void 0;\n      let isFirstChunk = true;\n      let isFirstDelta = true;\n      const transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(\n        new TransformStream({\n          async transform(chunk, controller) {\n            var _a22, _b, _c;\n            if (typeof chunk === \"object\" && chunk.type === \"stream-start\") {\n              warnings = chunk.warnings;\n              return;\n            }\n            if (isFirstChunk) {\n              msToFirstChunk = now2() - startTimestampMs;\n              isFirstChunk = false;\n            }\n            if (typeof chunk === \"string\") {\n              accumulatedText += chunk;\n              textDelta += chunk;\n              const { value: currentObjectJson, state: parseState } = await parsePartialJson(accumulatedText);\n              if (currentObjectJson !== void 0 && !isDeepEqualData(latestObjectJson, currentObjectJson)) {\n                const validationResult = await outputStrategy.validatePartialResult({\n                  value: currentObjectJson,\n                  textDelta,\n                  latestObject,\n                  isFirstDelta,\n                  isFinalDelta: parseState === \"successful-parse\"\n                });\n                if (validationResult.success && !isDeepEqualData(\n                  latestObject,\n                  validationResult.value.partial\n                )) {\n                  latestObjectJson = currentObjectJson;\n                  latestObject = validationResult.value.partial;\n                  controller.enqueue({\n                    type: \"object\",\n                    object: latestObject\n                  });\n                  controller.enqueue({\n                    type: \"text-delta\",\n                    textDelta: validationResult.value.textDelta\n                  });\n                  textDelta = \"\";\n                  isFirstDelta = false;\n                }\n              }\n              return;\n            }\n            switch (chunk.type) {\n              case \"response-metadata\": {\n                fullResponse = {\n                  id: (_a22 = chunk.id) != null ? _a22 : fullResponse.id,\n                  timestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,\n                  modelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId\n                };\n                break;\n              }\n              case \"finish\": {\n                if (textDelta !== \"\") {\n                  controller.enqueue({ type: \"text-delta\", textDelta });\n                }\n                finishReason = chunk.finishReason.unified;\n                usage = asLanguageModelUsage(chunk.usage);\n                providerMetadata = chunk.providerMetadata;\n                controller.enqueue({\n                  ...chunk,\n                  finishReason: chunk.finishReason.unified,\n                  usage,\n                  response: fullResponse\n                });\n                logWarnings({\n                  warnings: warnings != null ? warnings : [],\n                  provider: model.provider,\n                  model: model.modelId\n                });\n                self._usage.resolve(usage);\n                self._providerMetadata.resolve(providerMetadata);\n                self._warnings.resolve(warnings);\n                self._response.resolve({\n                  ...fullResponse,\n                  headers: response == null ? void 0 : response.headers\n                });\n                self._finishReason.resolve(finishReason != null ? finishReason : \"other\");\n                try {\n                  object2 = await parseAndValidateObjectResultWithRepair(\n                    accumulatedText,\n                    outputStrategy,\n                    repairText,\n                    {\n                      response: fullResponse,\n                      usage,\n                      finishReason\n                    }\n                  );\n                  self._object.resolve(object2);\n                } catch (e) {\n                  error = e;\n                  self._object.reject(e);\n                }\n                break;\n              }\n              default: {\n                controller.enqueue(chunk);\n                break;\n              }\n            }\n          },\n          async flush(controller) {\n            try {\n              const finalUsage = usage != null ? usage : {\n                promptTokens: NaN,\n                completionTokens: NaN,\n                totalTokens: NaN\n              };\n              await notify({\n                event: {\n                  callId,\n                  stepNumber: 0,\n                  provider: model.provider,\n                  modelId: model.modelId,\n                  finishReason: finishReason != null ? finishReason : \"other\",\n                  usage: finalUsage,\n                  objectText: accumulatedText,\n                  msToFirstChunk,\n                  reasoning: void 0,\n                  warnings,\n                  request: request != null ? request : {},\n                  response: {\n                    ...fullResponse,\n                    headers: response == null ? void 0 : response.headers\n                  },\n                  providerMetadata\n                },\n                callbacks: [\n                  onStepFinish,\n                  telemetryDispatcher.onObjectStepEnd\n                ]\n              });\n              await notify({\n                event: {\n                  callId,\n                  object: object2,\n                  error,\n                  reasoning: void 0,\n                  finishReason: finishReason != null ? finishReason : \"other\",\n                  usage: finalUsage,\n                  warnings,\n                  request: request != null ? request : {},\n                  response: {\n                    ...fullResponse,\n                    headers: response == null ? void 0 : response.headers\n                  },\n                  providerMetadata\n                },\n                callbacks: [onFinish, telemetryDispatcher.onEnd]\n              });\n            } catch (error2) {\n              controller.enqueue({ type: \"error\", error: error2 });\n            }\n          }\n        })\n      );\n      stitchableStream.addStream(transformedStream);\n    })().catch(async (error) => {\n      var _a22;\n      await ((_a22 = telemetryDispatcher.onError) == null ? void 0 : _a22.call(telemetryDispatcher, { callId, error }));\n      stitchableStream.addStream(\n        new ReadableStream({\n          start(controller) {\n            controller.enqueue({ type: \"error\", error });\n            controller.close();\n          }\n        })\n      );\n    }).finally(() => {\n      stitchableStream.close();\n    });\n    this.outputStrategy = outputStrategy;\n  }\n  get object() {\n    return this._object.promise;\n  }\n  get usage() {\n    return this._usage.promise;\n  }\n  get providerMetadata() {\n    return this._providerMetadata.promise;\n  }\n  get warnings() {\n    return this._warnings.promise;\n  }\n  get request() {\n    return this._request.promise;\n  }\n  get response() {\n    return this._response.promise;\n  }\n  get finishReason() {\n    return this._finishReason.promise;\n  }\n  get partialObjectStream() {\n    return createAsyncIterableStream(\n      this.baseStream.pipeThrough(\n        new TransformStream({\n          transform(chunk, controller) {\n            switch (chunk.type) {\n              case \"object\":\n                controller.enqueue(chunk.object);\n                break;\n              case \"text-delta\":\n              case \"finish\":\n              case \"error\":\n                break;\n              default: {\n                const _exhaustiveCheck = chunk;\n                throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n              }\n            }\n          }\n        })\n      )\n    );\n  }\n  get elementStream() {\n    return this.outputStrategy.createElementStream(this.baseStream);\n  }\n  get textStream() {\n    return createAsyncIterableStream(\n      this.baseStream.pipeThrough(\n        new TransformStream({\n          transform(chunk, controller) {\n            switch (chunk.type) {\n              case \"text-delta\":\n                controller.enqueue(chunk.textDelta);\n                break;\n              case \"object\":\n              case \"finish\":\n              case \"error\":\n                break;\n              default: {\n                const _exhaustiveCheck = chunk;\n                throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n              }\n            }\n          }\n        })\n      )\n    );\n  }\n  get fullStream() {\n    return createAsyncIterableStream(this.baseStream);\n  }\n  pipeTextStreamToResponse(response, init) {\n    pipeTextStreamToResponse({\n      response,\n      stream: this.textStream,\n      ...init\n    });\n  }\n  toTextStreamResponse(init) {\n    return createTextStreamResponse({\n      stream: this.textStream,\n      ...init\n    });\n  }\n};\n\n// src/generate-speech/generate-speech.ts\nimport {\n  detectMediaType as detectMediaType3,\n  withUserAgentSuffix as withUserAgentSuffix8\n} from \"@ai-sdk/provider-utils\";\n\n// src/generate-speech/generated-audio-file.ts\nvar DefaultGeneratedAudioFile = class extends DefaultGeneratedFile {\n  constructor({\n    data,\n    mediaType\n  }) {\n    super({ data, mediaType });\n    let format = \"mp3\";\n    if (mediaType) {\n      const mediaTypeParts = mediaType.split(\"/\");\n      if (mediaTypeParts.length === 2) {\n        if (mediaType !== \"audio/mpeg\") {\n          format = mediaTypeParts[1];\n        }\n      }\n    }\n    if (!format) {\n      throw new Error(\n        \"Audio format must be provided or determinable from media type\"\n      );\n    }\n    this.format = format;\n  }\n};\n\n// src/generate-speech/generate-speech.ts\nasync function generateSpeech({\n  model,\n  text: text2,\n  voice,\n  outputFormat,\n  instructions,\n  speed,\n  language,\n  providerOptions = {},\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers\n}) {\n  var _a22;\n  const resolvedModel = resolveSpeechModel(model);\n  if (!resolvedModel) {\n    throw new Error(\"Model could not be resolved\");\n  }\n  const headersWithUserAgent = withUserAgentSuffix8(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const result = await retry(\n    () => resolvedModel.doGenerate({\n      text: text2,\n      voice,\n      outputFormat,\n      instructions,\n      speed,\n      language,\n      abortSignal,\n      headers: headersWithUserAgent,\n      providerOptions\n    })\n  );\n  if (!result.audio || result.audio.length === 0) {\n    throw new NoSpeechGeneratedError({ responses: [result.response] });\n  }\n  logWarnings({\n    warnings: result.warnings,\n    provider: resolvedModel.provider,\n    model: resolvedModel.modelId\n  });\n  return new DefaultSpeechResult({\n    audio: new DefaultGeneratedAudioFile({\n      data: result.audio,\n      mediaType: (_a22 = detectMediaType3({\n        data: result.audio,\n        topLevelType: \"audio\"\n      })) != null ? _a22 : \"audio/mp3\"\n    }),\n    warnings: result.warnings,\n    responses: [result.response],\n    providerMetadata: result.providerMetadata\n  });\n}\nvar DefaultSpeechResult = class {\n  constructor(options) {\n    var _a22;\n    this.audio = options.audio;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = (_a22 = options.providerMetadata) != null ? _a22 : {};\n  }\n};\n\n// src/generate-speech/index.ts\nvar experimental_generateSpeech = generateSpeech;\n\n// src/generate-text/prune-messages.ts\nfunction pruneMessages({\n  messages,\n  reasoning = \"none\",\n  toolCalls = [],\n  emptyMessages = \"remove\"\n}) {\n  if (reasoning === \"all\" || reasoning === \"before-last-message\") {\n    messages = messages.map((message, messageIndex) => {\n      if (message.role !== \"assistant\" || typeof message.content === \"string\" || reasoning === \"before-last-message\" && messageIndex === messages.length - 1) {\n        return message;\n      }\n      return {\n        ...message,\n        content: message.content.filter((part) => part.type !== \"reasoning\")\n      };\n    });\n  }\n  if (toolCalls === \"none\") {\n    toolCalls = [];\n  } else if (toolCalls === \"all\") {\n    toolCalls = [{ type: \"all\" }];\n  } else if (toolCalls === \"before-last-message\") {\n    toolCalls = [{ type: \"before-last-message\" }];\n  } else if (typeof toolCalls === \"string\") {\n    toolCalls = [{ type: toolCalls }];\n  }\n  for (const toolCall of toolCalls) {\n    const keepLastMessagesCount = toolCall.type === \"all\" ? void 0 : toolCall.type === \"before-last-message\" ? 1 : Number(\n      toolCall.type.slice(\"before-last-\".length).slice(0, -\"-messages\".length)\n    );\n    const keptToolCallIds = /* @__PURE__ */ new Set();\n    const keptApprovalIds = /* @__PURE__ */ new Set();\n    if (keepLastMessagesCount != null) {\n      for (const message of messages.slice(-keepLastMessagesCount)) {\n        if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n          for (const part of message.content) {\n            if (part.type === \"tool-call\" || part.type === \"tool-result\") {\n              keptToolCallIds.add(part.toolCallId);\n            } else if (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") {\n              keptApprovalIds.add(part.approvalId);\n            }\n          }\n        }\n      }\n    }\n    messages = messages.map((message, messageIndex) => {\n      if (message.role !== \"assistant\" && message.role !== \"tool\" || typeof message.content === \"string\" || keepLastMessagesCount && messageIndex >= messages.length - keepLastMessagesCount) {\n        return message;\n      }\n      const toolCallIdToToolName = {};\n      const approvalIdToToolName = {};\n      return {\n        ...message,\n        content: message.content.filter((part) => {\n          if (part.type !== \"tool-call\" && part.type !== \"tool-result\" && part.type !== \"tool-approval-request\" && part.type !== \"tool-approval-response\") {\n            return true;\n          }\n          if (part.type === \"tool-call\") {\n            toolCallIdToToolName[part.toolCallId] = part.toolName;\n          } else if (part.type === \"tool-approval-request\") {\n            approvalIdToToolName[part.approvalId] = toolCallIdToToolName[part.toolCallId];\n          }\n          if ((part.type === \"tool-call\" || part.type === \"tool-result\") && keptToolCallIds.has(part.toolCallId) || (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") && keptApprovalIds.has(part.approvalId)) {\n            return true;\n          }\n          return toolCall.tools != null && !toolCall.tools.includes(\n            part.type === \"tool-call\" || part.type === \"tool-result\" ? part.toolName : approvalIdToToolName[part.approvalId]\n          );\n        })\n      };\n    });\n  }\n  if (emptyMessages === \"remove\") {\n    messages = messages.filter((message) => message.content.length > 0);\n  }\n  return messages;\n}\n\n// src/generate-text/smooth-stream.ts\nimport { delay as originalDelay } from \"@ai-sdk/provider-utils\";\nimport {\n  InvalidArgumentError as InvalidArgumentError2\n} from \"@ai-sdk/provider\";\nvar CHUNKING_REGEXPS = {\n  word: /\\S+\\s+/m,\n  line: /\\n+/m\n};\nfunction smoothStream({\n  delayInMs = 10,\n  chunking = \"word\",\n  _internal: { delay: delay2 = originalDelay } = {}\n} = {}) {\n  let detectChunk;\n  if (chunking != null && typeof chunking === \"object\" && \"segment\" in chunking && typeof chunking.segment === \"function\") {\n    const segmenter = chunking;\n    detectChunk = (buffer) => {\n      if (buffer.length === 0)\n        return null;\n      const iterator = segmenter.segment(buffer)[Symbol.iterator]();\n      const first = iterator.next().value;\n      return (first == null ? void 0 : first.segment) || null;\n    };\n  } else if (typeof chunking === \"function\") {\n    detectChunk = (buffer) => {\n      const match = chunking(buffer);\n      if (match == null) {\n        return null;\n      }\n      if (!match.length) {\n        throw new Error(`Chunking function must return a non-empty string.`);\n      }\n      if (!buffer.startsWith(match)) {\n        throw new Error(\n          `Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`\n        );\n      }\n      return match;\n    };\n  } else {\n    const chunkingRegex = typeof chunking === \"string\" ? CHUNKING_REGEXPS[chunking] : chunking instanceof RegExp ? chunking : void 0;\n    if (chunkingRegex == null) {\n      throw new InvalidArgumentError2({\n        argument: \"chunking\",\n        message: `Chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a ChunkDetector function. Received: ${chunking}`\n      });\n    }\n    detectChunk = (buffer) => {\n      const match = chunkingRegex.exec(buffer);\n      if (!match) {\n        return null;\n      }\n      return buffer.slice(0, match.index) + (match == null ? void 0 : match[0]);\n    };\n  }\n  return () => {\n    let buffer = \"\";\n    let id = \"\";\n    let type = void 0;\n    let providerMetadata = void 0;\n    function flushBuffer(controller) {\n      if (buffer.length > 0 && type !== void 0) {\n        controller.enqueue({\n          type,\n          text: buffer,\n          id,\n          ...providerMetadata != null ? { providerMetadata } : {}\n        });\n        buffer = \"\";\n        providerMetadata = void 0;\n      }\n    }\n    return new TransformStream({\n      async transform(chunk, controller) {\n        if (chunk.type !== \"text-delta\" && chunk.type !== \"reasoning-delta\") {\n          flushBuffer(controller);\n          controller.enqueue(chunk);\n          return;\n        }\n        if ((chunk.type !== type || chunk.id !== id) && buffer.length > 0) {\n          flushBuffer(controller);\n        }\n        buffer += chunk.text;\n        id = chunk.id;\n        type = chunk.type;\n        if (chunk.providerMetadata != null) {\n          providerMetadata = chunk.providerMetadata;\n        }\n        let match;\n        while ((match = detectChunk(buffer)) != null) {\n          controller.enqueue({ type, text: match, id });\n          buffer = buffer.slice(match.length);\n          await delay2(delayInMs);\n        }\n      }\n    });\n  };\n}\n\n// src/generate-video/generate-video.ts\nimport {\n  convertBase64ToUint8Array as convertBase64ToUint8Array5,\n  withUserAgentSuffix as withUserAgentSuffix9,\n  detectMediaType as detectMediaType4\n} from \"@ai-sdk/provider-utils\";\nvar defaultDownload = createDownload();\nasync function experimental_generateVideo({\n  model: modelArg,\n  prompt: promptArg,\n  n = 1,\n  maxVideosPerCall,\n  aspectRatio,\n  resolution,\n  duration,\n  fps,\n  seed,\n  generateAudio,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  download: downloadFn = defaultDownload\n}) {\n  var _a22;\n  const model = resolveVideoModel(modelArg);\n  const headersWithUserAgent = withUserAgentSuffix9(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const { prompt, image } = normalizePrompt2(promptArg);\n  const maxVideosPerCallWithDefault = (_a22 = maxVideosPerCall != null ? maxVideosPerCall : await invokeModelMaxVideosPerCall(model)) != null ? _a22 : 1;\n  const callCount = Math.ceil(n / maxVideosPerCallWithDefault);\n  const callVideoCounts = Array.from({ length: callCount }, (_, index) => {\n    const remaining = n - index * maxVideosPerCallWithDefault;\n    return Math.min(remaining, maxVideosPerCallWithDefault);\n  });\n  const results = await Promise.all(\n    callVideoCounts.map(\n      async (callVideoCount) => await retry(\n        () => model.doGenerate({\n          prompt,\n          n: callVideoCount,\n          aspectRatio,\n          resolution,\n          duration,\n          fps,\n          seed,\n          generateAudio,\n          image,\n          providerOptions: providerOptions != null ? providerOptions : {},\n          headers: headersWithUserAgent,\n          abortSignal\n        })\n      )\n    )\n  );\n  const videos = [];\n  const warnings = [];\n  const responses = [];\n  const providerMetadata = {};\n  for (const result of results) {\n    for (const videoData of result.videos) {\n      switch (videoData.type) {\n        case \"url\": {\n          const { data, mediaType: downloadedMediaType } = await downloadFn({\n            url: new URL(videoData.url),\n            abortSignal\n          });\n          const isUsableMediaType = (type) => !!type && type !== \"application/octet-stream\";\n          const mediaType = isUsableMediaType(videoData.mediaType) && videoData.mediaType || isUsableMediaType(downloadedMediaType) && downloadedMediaType || detectMediaType4({\n            data,\n            topLevelType: \"video\"\n          }) || \"video/mp4\";\n          videos.push(\n            new DefaultGeneratedFile({\n              data,\n              mediaType\n            })\n          );\n          break;\n        }\n        case \"base64\": {\n          videos.push(\n            new DefaultGeneratedFile({\n              data: videoData.data,\n              mediaType: videoData.mediaType || \"video/mp4\"\n            })\n          );\n          break;\n        }\n        case \"binary\": {\n          const mediaType = videoData.mediaType || detectMediaType4({\n            data: videoData.data,\n            topLevelType: \"video\"\n          }) || \"video/mp4\";\n          videos.push(\n            new DefaultGeneratedFile({\n              data: videoData.data,\n              mediaType\n            })\n          );\n          break;\n        }\n      }\n    }\n    warnings.push(...result.warnings);\n    responses.push({\n      timestamp: result.response.timestamp,\n      modelId: result.response.modelId,\n      headers: result.response.headers,\n      providerMetadata: result.providerMetadata\n    });\n    if (result.providerMetadata != null) {\n      for (const [providerName, metadata] of Object.entries(\n        result.providerMetadata\n      )) {\n        const existingMetadata = providerMetadata[providerName];\n        if (existingMetadata != null && typeof existingMetadata === \"object\") {\n          providerMetadata[providerName] = {\n            ...existingMetadata,\n            ...metadata\n          };\n          if (\"videos\" in existingMetadata && Array.isArray(existingMetadata.videos) && \"videos\" in metadata && Array.isArray(metadata.videos)) {\n            providerMetadata[providerName].videos = [\n              ...existingMetadata.videos,\n              ...metadata.videos\n            ];\n          }\n        } else {\n          providerMetadata[providerName] = metadata;\n        }\n      }\n    }\n  }\n  if (videos.length === 0) {\n    throw new NoVideoGeneratedError({ responses });\n  }\n  if (warnings.length > 0) {\n    logWarnings({\n      warnings,\n      provider: model.provider,\n      model: model.modelId\n    });\n  }\n  return {\n    video: videos[0],\n    videos,\n    warnings,\n    responses,\n    providerMetadata\n  };\n}\nfunction normalizePrompt2(promptArg) {\n  var _a22, _b;\n  if (typeof promptArg === \"string\") {\n    return {\n      prompt: promptArg,\n      image: void 0\n    };\n  }\n  let image;\n  if (promptArg.image != null) {\n    const dataContent = promptArg.image;\n    if (typeof dataContent === \"string\") {\n      if (dataContent.startsWith(\"http://\") || dataContent.startsWith(\"https://\")) {\n        image = {\n          type: \"url\",\n          url: dataContent\n        };\n      } else if (dataContent.startsWith(\"data:\")) {\n        const { mediaType, base64Content } = splitDataUrl(dataContent);\n        image = {\n          type: \"file\",\n          mediaType: mediaType != null ? mediaType : \"image/png\",\n          data: convertBase64ToUint8Array5(base64Content != null ? base64Content : \"\")\n        };\n      } else {\n        const bytes = convertBase64ToUint8Array5(dataContent);\n        const mediaType = (_a22 = detectMediaType4({\n          data: bytes,\n          topLevelType: \"image\"\n        })) != null ? _a22 : \"image/png\";\n        image = {\n          type: \"file\",\n          mediaType,\n          data: bytes\n        };\n      }\n    } else if (dataContent instanceof Uint8Array) {\n      const mediaType = (_b = detectMediaType4({\n        data: dataContent,\n        topLevelType: \"image\"\n      })) != null ? _b : \"image/png\";\n      image = {\n        type: \"file\",\n        mediaType,\n        data: dataContent\n      };\n    }\n  }\n  return {\n    prompt: promptArg.text,\n    image\n  };\n}\nasync function invokeModelMaxVideosPerCall(model) {\n  if (typeof model.maxVideosPerCall === \"function\") {\n    return await model.maxVideosPerCall({ modelId: model.modelId });\n  }\n  return model.maxVideosPerCall;\n}\n\n// src/middleware/default-embedding-settings-middleware.ts\nfunction defaultEmbeddingSettingsMiddleware({\n  settings\n}) {\n  return {\n    specificationVersion: \"v4\",\n    transformParams: async ({ params }) => {\n      return mergeObjects(settings, params);\n    }\n  };\n}\n\n// src/middleware/default-settings-middleware.ts\nfunction defaultSettingsMiddleware({\n  settings\n}) {\n  return {\n    specificationVersion: \"v4\",\n    transformParams: async ({ params }) => {\n      return mergeObjects(settings, params);\n    }\n  };\n}\n\n// src/middleware/extract-json-middleware.ts\nfunction defaultTransform(text2) {\n  return text2.replace(/^```(?:json)?\\s*\\n?/, \"\").replace(/\\n?```\\s*$/, \"\").trim();\n}\nfunction extractJsonMiddleware(options) {\n  var _a22;\n  const transform = (_a22 = options == null ? void 0 : options.transform) != null ? _a22 : defaultTransform;\n  const hasCustomTransform = (options == null ? void 0 : options.transform) !== void 0;\n  return {\n    specificationVersion: \"v4\",\n    wrapGenerate: async ({ doGenerate }) => {\n      const { content, ...rest } = await doGenerate();\n      const transformedContent = [];\n      for (const part of content) {\n        if (part.type !== \"text\") {\n          transformedContent.push(part);\n          continue;\n        }\n        transformedContent.push({\n          ...part,\n          text: transform(part.text)\n        });\n      }\n      return { content: transformedContent, ...rest };\n    },\n    wrapStream: async ({ doStream }) => {\n      const { stream, ...rest } = await doStream();\n      const textBlocks = createIdMap();\n      const SUFFIX_BUFFER_SIZE = 12;\n      return {\n        stream: stream.pipeThrough(\n          new TransformStream({\n            transform: (chunk, controller) => {\n              if (chunk.type === \"text-start\") {\n                textBlocks[chunk.id] = {\n                  startEvent: chunk,\n                  // Custom transforms need to buffer all content\n                  phase: hasCustomTransform ? \"buffering\" : \"prefix\",\n                  buffer: \"\",\n                  prefixStripped: false\n                };\n                return;\n              }\n              if (chunk.type === \"text-delta\") {\n                const block = textBlocks[chunk.id];\n                if (!block) {\n                  controller.enqueue(chunk);\n                  return;\n                }\n                block.buffer += chunk.delta;\n                if (block.phase === \"buffering\") {\n                  return;\n                }\n                if (block.phase === \"prefix\") {\n                  if (block.buffer.length > 0 && !block.buffer.startsWith(\"`\")) {\n                    block.phase = \"streaming\";\n                    controller.enqueue(block.startEvent);\n                  } else if (block.buffer.startsWith(\"```\")) {\n                    if (block.buffer.includes(\"\\n\")) {\n                      const prefixMatch = block.buffer.match(/^```(?:json)?\\s*\\n/);\n                      if (prefixMatch) {\n                        block.buffer = block.buffer.slice(\n                          prefixMatch[0].length\n                        );\n                        block.prefixStripped = true;\n                        block.phase = \"streaming\";\n                        controller.enqueue(block.startEvent);\n                      } else {\n                        block.phase = \"streaming\";\n                        controller.enqueue(block.startEvent);\n                      }\n                    }\n                  } else if (block.buffer.length >= 3 && !block.buffer.startsWith(\"```\")) {\n                    block.phase = \"streaming\";\n                    controller.enqueue(block.startEvent);\n                  }\n                }\n                if (block.phase === \"streaming\" && block.buffer.length > SUFFIX_BUFFER_SIZE) {\n                  const toStream = block.buffer.slice(0, -SUFFIX_BUFFER_SIZE);\n                  block.buffer = block.buffer.slice(-SUFFIX_BUFFER_SIZE);\n                  controller.enqueue({\n                    type: \"text-delta\",\n                    id: chunk.id,\n                    delta: toStream\n                  });\n                }\n                return;\n              }\n              if (chunk.type === \"text-end\") {\n                const block = textBlocks[chunk.id];\n                if (block) {\n                  if (block.phase === \"prefix\" || block.phase === \"buffering\") {\n                    controller.enqueue(block.startEvent);\n                  }\n                  let remaining = block.buffer;\n                  if (block.phase === \"buffering\") {\n                    remaining = transform(remaining);\n                  } else if (block.prefixStripped) {\n                    remaining = remaining.replace(/\\n?```\\s*$/, \"\").trimEnd();\n                  } else {\n                    remaining = transform(remaining);\n                  }\n                  if (remaining.length > 0) {\n                    controller.enqueue({\n                      type: \"text-delta\",\n                      id: chunk.id,\n                      delta: remaining\n                    });\n                  }\n                  controller.enqueue(chunk);\n                  delete textBlocks[chunk.id];\n                  return;\n                }\n              }\n              controller.enqueue(chunk);\n            }\n          })\n        ),\n        ...rest\n      };\n    }\n  };\n}\n\n// src/util/get-potential-start-index.ts\nfunction getPotentialStartIndex(text2, searchedText) {\n  if (searchedText.length === 0) {\n    return null;\n  }\n  const directIndex = text2.indexOf(searchedText);\n  if (directIndex !== -1) {\n    return directIndex;\n  }\n  for (let i = text2.length - 1; i >= 0; i--) {\n    const suffix = text2.substring(i);\n    if (searchedText.startsWith(suffix)) {\n      return i;\n    }\n  }\n  return null;\n}\n\n// src/middleware/extract-reasoning-middleware.ts\nfunction extractReasoningMiddleware({\n  tagName,\n  separator = \"\\n\",\n  startWithReasoning = false\n}) {\n  const openingTag = `<${tagName}>`;\n  const closingTag = `</${tagName}>`;\n  return {\n    specificationVersion: \"v4\",\n    wrapGenerate: async ({ doGenerate }) => {\n      const { content, ...rest } = await doGenerate();\n      const transformedContent = [];\n      for (const part of content) {\n        if (part.type !== \"text\") {\n          transformedContent.push(part);\n          continue;\n        }\n        const text2 = startWithReasoning ? openingTag + part.text : part.text;\n        const regexp = new RegExp(`${openingTag}(.*?)${closingTag}`, \"gs\");\n        const matches = Array.from(text2.matchAll(regexp));\n        if (!matches.length) {\n          transformedContent.push(part);\n          continue;\n        }\n        const reasoningText = matches.map((match) => match[1]).join(separator);\n        let textWithoutReasoning = text2;\n        for (let i = matches.length - 1; i >= 0; i--) {\n          const match = matches[i];\n          const beforeMatch = textWithoutReasoning.slice(0, match.index);\n          const afterMatch = textWithoutReasoning.slice(\n            match.index + match[0].length\n          );\n          textWithoutReasoning = beforeMatch + (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : \"\") + afterMatch;\n        }\n        transformedContent.push({\n          type: \"reasoning\",\n          text: reasoningText\n        });\n        transformedContent.push({\n          type: \"text\",\n          text: textWithoutReasoning\n        });\n      }\n      return { content: transformedContent, ...rest };\n    },\n    wrapStream: async ({ doStream }) => {\n      const { stream, ...rest } = await doStream();\n      const reasoningExtractions = createIdMap();\n      let delayedTextStart;\n      return {\n        stream: stream.pipeThrough(\n          new TransformStream({\n            transform: (chunk, controller) => {\n              if (chunk.type === \"text-start\") {\n                delayedTextStart = chunk;\n                return;\n              }\n              if (chunk.type === \"text-end\" && delayedTextStart) {\n                controller.enqueue(delayedTextStart);\n                delayedTextStart = void 0;\n              }\n              if (chunk.type !== \"text-delta\") {\n                controller.enqueue(chunk);\n                return;\n              }\n              if (reasoningExtractions[chunk.id] == null) {\n                reasoningExtractions[chunk.id] = {\n                  isFirstReasoning: true,\n                  isFirstText: true,\n                  afterSwitch: false,\n                  isReasoning: startWithReasoning,\n                  buffer: \"\",\n                  idCounter: 0,\n                  textId: chunk.id\n                };\n              }\n              const activeExtraction = reasoningExtractions[chunk.id];\n              activeExtraction.buffer += chunk.delta;\n              function publish(text2) {\n                if (text2.length > 0) {\n                  const prefix = activeExtraction.afterSwitch && (activeExtraction.isReasoning ? !activeExtraction.isFirstReasoning : !activeExtraction.isFirstText) ? separator : \"\";\n                  if (activeExtraction.isReasoning && (activeExtraction.afterSwitch || activeExtraction.isFirstReasoning)) {\n                    controller.enqueue({\n                      type: \"reasoning-start\",\n                      id: `reasoning-${activeExtraction.idCounter}`\n                    });\n                  }\n                  if (activeExtraction.isReasoning) {\n                    controller.enqueue({\n                      type: \"reasoning-delta\",\n                      delta: prefix + text2,\n                      id: `reasoning-${activeExtraction.idCounter}`\n                    });\n                  } else {\n                    if (delayedTextStart) {\n                      controller.enqueue(delayedTextStart);\n                      delayedTextStart = void 0;\n                    }\n                    controller.enqueue({\n                      type: \"text-delta\",\n                      delta: prefix + text2,\n                      id: activeExtraction.textId\n                    });\n                  }\n                  activeExtraction.afterSwitch = false;\n                  if (activeExtraction.isReasoning) {\n                    activeExtraction.isFirstReasoning = false;\n                  } else {\n                    activeExtraction.isFirstText = false;\n                  }\n                }\n              }\n              do {\n                const nextTag = activeExtraction.isReasoning ? closingTag : openingTag;\n                const startIndex = getPotentialStartIndex(\n                  activeExtraction.buffer,\n                  nextTag\n                );\n                if (startIndex == null) {\n                  publish(activeExtraction.buffer);\n                  activeExtraction.buffer = \"\";\n                  break;\n                }\n                publish(activeExtraction.buffer.slice(0, startIndex));\n                const foundFullMatch = startIndex + nextTag.length <= activeExtraction.buffer.length;\n                if (foundFullMatch) {\n                  activeExtraction.buffer = activeExtraction.buffer.slice(\n                    startIndex + nextTag.length\n                  );\n                  if (activeExtraction.isReasoning) {\n                    if (activeExtraction.isFirstReasoning) {\n                      controller.enqueue({\n                        type: \"reasoning-start\",\n                        id: `reasoning-${activeExtraction.idCounter}`\n                      });\n                    }\n                    controller.enqueue({\n                      type: \"reasoning-end\",\n                      id: `reasoning-${activeExtraction.idCounter++}`\n                    });\n                  }\n                  activeExtraction.isReasoning = !activeExtraction.isReasoning;\n                  activeExtraction.afterSwitch = true;\n                } else {\n                  activeExtraction.buffer = activeExtraction.buffer.slice(startIndex);\n                  break;\n                }\n              } while (true);\n            }\n          })\n        ),\n        ...rest\n      };\n    }\n  };\n}\n\n// src/middleware/simulate-streaming-middleware.ts\nfunction simulateStreamingMiddleware() {\n  return {\n    specificationVersion: \"v4\",\n    wrapStream: async ({ doGenerate }) => {\n      const result = await doGenerate();\n      let id = 0;\n      const simulatedStream = new ReadableStream({\n        start(controller) {\n          controller.enqueue({\n            type: \"stream-start\",\n            warnings: result.warnings\n          });\n          controller.enqueue({ type: \"response-metadata\", ...result.response });\n          for (const part of result.content) {\n            switch (part.type) {\n              case \"text\": {\n                if (part.text.length > 0) {\n                  controller.enqueue({ type: \"text-start\", id: String(id) });\n                  controller.enqueue({\n                    type: \"text-delta\",\n                    id: String(id),\n                    delta: part.text\n                  });\n                  controller.enqueue({ type: \"text-end\", id: String(id) });\n                  id++;\n                }\n                break;\n              }\n              case \"reasoning\": {\n                controller.enqueue({\n                  type: \"reasoning-start\",\n                  id: String(id),\n                  providerMetadata: part.providerMetadata\n                });\n                controller.enqueue({\n                  type: \"reasoning-delta\",\n                  id: String(id),\n                  delta: part.text\n                });\n                controller.enqueue({ type: \"reasoning-end\", id: String(id) });\n                id++;\n                break;\n              }\n              default: {\n                controller.enqueue(part);\n                break;\n              }\n            }\n          }\n          controller.enqueue({\n            type: \"finish\",\n            finishReason: result.finishReason,\n            usage: result.usage,\n            providerMetadata: result.providerMetadata\n          });\n          controller.close();\n        }\n      });\n      return {\n        stream: simulatedStream,\n        request: result.request,\n        response: result.response\n      };\n    }\n  };\n}\n\n// src/middleware/add-tool-input-examples-middleware.ts\nfunction defaultFormatExample(example) {\n  return JSON.stringify(example.input);\n}\nfunction addToolInputExamplesMiddleware({\n  prefix = \"Input Examples:\",\n  format = defaultFormatExample,\n  remove = true\n} = {}) {\n  return {\n    specificationVersion: \"v4\",\n    transformParams: async ({ params }) => {\n      var _a22;\n      if (!((_a22 = params.tools) == null ? void 0 : _a22.length)) {\n        return params;\n      }\n      const transformedTools = params.tools.map((tool2) => {\n        var _a23;\n        if (tool2.type !== \"function\" || !((_a23 = tool2.inputExamples) == null ? void 0 : _a23.length)) {\n          return tool2;\n        }\n        const formattedExamples = tool2.inputExamples.map((example, index) => format(example, index)).join(\"\\n\");\n        const examplesSection = `${prefix}\n${formattedExamples}`;\n        const toolDescription = tool2.description ? `${tool2.description}\n\n${examplesSection}` : examplesSection;\n        return {\n          ...tool2,\n          description: toolDescription,\n          inputExamples: remove ? void 0 : tool2.inputExamples\n        };\n      });\n      return {\n        ...params,\n        tools: transformedTools\n      };\n    }\n  };\n}\n\n// src/middleware/wrap-language-model.ts\nimport { asArray as asArray7 } from \"@ai-sdk/provider-utils\";\nvar wrapLanguageModel = ({\n  model: inputModel,\n  middleware: middlewareArg,\n  modelId,\n  providerId\n}) => {\n  const model = asLanguageModelV4(inputModel);\n  return [...asArray7(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n    return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n  }, model);\n};\nvar doWrap = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapGenerate,\n    wrapStream,\n    overrideProvider,\n    overrideModelId,\n    overrideSupportedUrls\n  },\n  modelId,\n  providerId\n}) => {\n  var _a22, _b, _c;\n  async function doTransform({\n    params,\n    type\n  }) {\n    return transformParams ? await transformParams({ params, type, model }) : params;\n  }\n  return {\n    specificationVersion: \"v4\",\n    provider: (_a22 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a22 : model.provider,\n    modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n    supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,\n    async doGenerate(params) {\n      const transformedParams = await doTransform({ params, type: \"generate\" });\n      const doGenerate = async () => await model.doGenerate(transformedParams);\n      const doStream = async () => await model.doStream(transformedParams);\n      return wrapGenerate ? await wrapGenerate({\n        doGenerate,\n        doStream,\n        params: transformedParams,\n        model\n      }) : await doGenerate();\n    },\n    async doStream(params) {\n      const transformedParams = await doTransform({ params, type: \"stream\" });\n      const doGenerate = async () => await model.doGenerate(transformedParams);\n      const doStream = async () => await model.doStream(transformedParams);\n      return wrapStream ? await wrapStream({\n        doGenerate,\n        doStream,\n        params: transformedParams,\n        model\n      }) : await doStream();\n    }\n  };\n};\n\n// src/middleware/wrap-embedding-model.ts\nimport { asArray as asArray8 } from \"@ai-sdk/provider-utils\";\nvar wrapEmbeddingModel = ({\n  model: inputModel,\n  middleware: middlewareArg,\n  modelId,\n  providerId\n}) => {\n  const model = asEmbeddingModelV4(inputModel);\n  return [...asArray8(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n    return doWrap2({ model: wrappedModel, middleware, modelId, providerId });\n  }, model);\n};\nvar doWrap2 = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapEmbed,\n    overrideProvider,\n    overrideModelId,\n    overrideMaxEmbeddingsPerCall,\n    overrideSupportsParallelCalls\n  },\n  modelId,\n  providerId\n}) => {\n  var _a22, _b, _c, _d;\n  async function doTransform({\n    params\n  }) {\n    return transformParams ? await transformParams({ params, model }) : params;\n  }\n  return {\n    specificationVersion: \"v4\",\n    provider: (_a22 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a22 : model.provider,\n    modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n    maxEmbeddingsPerCall: (_c = overrideMaxEmbeddingsPerCall == null ? void 0 : overrideMaxEmbeddingsPerCall({ model })) != null ? _c : model.maxEmbeddingsPerCall,\n    supportsParallelCalls: (_d = overrideSupportsParallelCalls == null ? void 0 : overrideSupportsParallelCalls({ model })) != null ? _d : model.supportsParallelCalls,\n    async doEmbed(params) {\n      const transformedParams = await doTransform({ params });\n      const doEmbed = async () => await model.doEmbed(transformedParams);\n      return wrapEmbed ? await wrapEmbed({\n        doEmbed,\n        params: transformedParams,\n        model\n      }) : await doEmbed();\n    }\n  };\n};\n\n// src/middleware/wrap-image-model.ts\nimport { asArray as asArray9 } from \"@ai-sdk/provider-utils\";\nvar wrapImageModel = ({\n  model: inputModel,\n  middleware: middlewareArg,\n  modelId,\n  providerId\n}) => {\n  const model = asImageModelV4(inputModel);\n  return [...asArray9(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n    return doWrap3({ model: wrappedModel, middleware, modelId, providerId });\n  }, model);\n};\nvar doWrap3 = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapGenerate,\n    overrideProvider,\n    overrideModelId,\n    overrideMaxImagesPerCall\n  },\n  modelId,\n  providerId\n}) => {\n  var _a22, _b, _c;\n  async function doTransform({ params }) {\n    return transformParams ? await transformParams({ params, model }) : params;\n  }\n  const maxImagesPerCallRaw = (_a22 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a22 : model.maxImagesPerCall;\n  const maxImagesPerCall = maxImagesPerCallRaw instanceof Function ? maxImagesPerCallRaw.bind(model) : maxImagesPerCallRaw;\n  return {\n    specificationVersion: \"v4\",\n    provider: (_b = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _b : model.provider,\n    modelId: (_c = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _c : model.modelId,\n    maxImagesPerCall,\n    async doGenerate(params) {\n      const transformedParams = await doTransform({ params });\n      const doGenerate = async () => await model.doGenerate(transformedParams);\n      return wrapGenerate ? await wrapGenerate({\n        doGenerate,\n        params: transformedParams,\n        model\n      }) : await doGenerate();\n    }\n  };\n};\n\n// src/middleware/wrap-provider.ts\nfunction wrapProvider({\n  provider,\n  languageModelMiddleware,\n  imageModelMiddleware\n}) {\n  const providerV4 = asProviderV4(provider);\n  return {\n    specificationVersion: \"v4\",\n    languageModel: (modelId) => wrapLanguageModel({\n      model: providerV4.languageModel(modelId),\n      middleware: languageModelMiddleware\n    }),\n    embeddingModel: providerV4.embeddingModel,\n    imageModel: (modelId) => {\n      let model = providerV4.imageModel(modelId);\n      if (imageModelMiddleware != null) {\n        model = wrapImageModel({ model, middleware: imageModelMiddleware });\n      }\n      return model;\n    },\n    transcriptionModel: providerV4.transcriptionModel,\n    speechModel: providerV4.speechModel,\n    rerankingModel: providerV4.rerankingModel\n  };\n}\n\n// src/realtime/audio-utils.ts\nfunction encodeRealtimeAudio(float32Array) {\n  const buffer = new ArrayBuffer(float32Array.length * 2);\n  const view = new DataView(buffer);\n  for (let i = 0; i < float32Array.length; i++) {\n    const s = Math.max(-1, Math.min(1, float32Array[i]));\n    view.setInt16(i * 2, s < 0 ? s * 32768 : s * 32767, true);\n  }\n  const bytes = new Uint8Array(buffer);\n  const chunkSize = 32768;\n  let binary = \"\";\n  for (let i = 0; i < bytes.length; i += chunkSize) {\n    const chunk = bytes.subarray(i, i + chunkSize);\n    binary += String.fromCharCode(...chunk);\n  }\n  return btoa(binary);\n}\nfunction decodeRealtimeAudio(base64Audio) {\n  const binaryString = atob(base64Audio);\n  const bytes = new Uint8Array(binaryString.length);\n  for (let i = 0; i < binaryString.length; i++) {\n    bytes[i] = binaryString.charCodeAt(i);\n  }\n  const pcm16 = new Int16Array(bytes.buffer);\n  const float32 = new Float32Array(pcm16.length);\n  for (let i = 0; i < pcm16.length; i++) {\n    float32[i] = pcm16[i] / 32768;\n  }\n  return float32;\n}\nfunction resampleAudio(input, inputRate, outputRate) {\n  if (inputRate === outputRate) {\n    return input;\n  }\n  const ratio = inputRate / outputRate;\n  const outputLength = Math.round(input.length / ratio);\n  const output = new Float32Array(outputLength);\n  for (let i = 0; i < outputLength; i++) {\n    const srcIndex = i * ratio;\n    const srcIndexFloor = Math.floor(srcIndex);\n    const srcIndexCeil = Math.min(srcIndexFloor + 1, input.length - 1);\n    const fraction = srcIndex - srcIndexFloor;\n    output[i] = input[srcIndexFloor] * (1 - fraction) + input[srcIndexCeil] * fraction;\n  }\n  return output;\n}\n\n// src/realtime/get-realtime-tool-definitions.ts\nimport {\n  asSchema as asSchema6\n} from \"@ai-sdk/provider-utils\";\nasync function getRealtimeToolDefinitions({\n  tools,\n  toolsContext = {}\n}) {\n  const definitions = [];\n  for (const [name22, tool2] of Object.entries(tools)) {\n    const toolType = tool2.type;\n    switch (toolType) {\n      case void 0:\n      case \"function\":\n      case \"dynamic\": {\n        const description = resolveRealtimeToolDescription({\n          tool: tool2,\n          toolName: name22,\n          toolsContext\n        });\n        definitions.push({\n          type: \"function\",\n          name: name22,\n          description,\n          parameters: await asSchema6(tool2.inputSchema).jsonSchema\n        });\n        break;\n      }\n      case \"provider\":\n        break;\n      default: {\n        const exhaustiveCheck = toolType;\n        throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n      }\n    }\n  }\n  return definitions;\n}\nfunction resolveRealtimeToolDescription({\n  tool: tool2,\n  toolName,\n  toolsContext\n}) {\n  return tool2.description === void 0 ? void 0 : typeof tool2.description === \"string\" ? tool2.description : tool2.description({\n    context: toolsContext[toolName]\n  });\n}\n\n// src/realtime/browser-realtime-audio.ts\nvar BrowserRealtimeAudio = class {\n  constructor(options) {\n    this.captureContext = null;\n    this.captureProcessor = null;\n    this.captureSource = null;\n    this.captureStream = null;\n    this.playbackContext = null;\n    this.playbackQueue = [];\n    this.playbackTime = 0;\n    this.playbackStartTime = 0;\n    this.activeSources = /* @__PURE__ */ new Set();\n    this.isPlaying = false;\n    this.captureSampleRate = options.captureSampleRate;\n    this.playbackSampleRate = options.playbackSampleRate;\n    this.onAudio = options.onAudio;\n    this.onPlayingChange = options.onPlayingChange;\n    this.onCapturingChange = options.onCapturingChange;\n  }\n  ensurePlaybackContext() {\n    if (this.playbackContext == null) {\n      this.playbackContext = new AudioContext({\n        sampleRate: this.playbackSampleRate\n      });\n    }\n  }\n  startCapture(stream) {\n    const ctx = new AudioContext({ sampleRate: this.captureSampleRate });\n    this.captureContext = ctx;\n    this.captureStream = stream;\n    const source = ctx.createMediaStreamSource(stream);\n    this.captureSource = source;\n    const processor = ctx.createScriptProcessor(4096, 1, 1);\n    this.captureProcessor = processor;\n    processor.onaudioprocess = (event) => {\n      const inputData = event.inputBuffer.getChannelData(0);\n      const samples = resampleAudio(\n        new Float32Array(inputData),\n        ctx.sampleRate,\n        this.captureSampleRate\n      );\n      this.onAudio(encodeRealtimeAudio(samples));\n    };\n    source.connect(processor);\n    processor.connect(ctx.destination);\n    this.onCapturingChange(true);\n  }\n  stopCapture() {\n    var _a22, _b, _c, _d;\n    (_a22 = this.captureProcessor) == null ? void 0 : _a22.disconnect();\n    (_b = this.captureSource) == null ? void 0 : _b.disconnect();\n    void ((_c = this.captureContext) == null ? void 0 : _c.close());\n    (_d = this.captureStream) == null ? void 0 : _d.getTracks().forEach((track) => track.stop());\n    this.captureProcessor = null;\n    this.captureSource = null;\n    this.captureContext = null;\n    this.captureStream = null;\n    this.onCapturingChange(false);\n  }\n  playAudio(base64Audio) {\n    this.ensurePlaybackContext();\n    this.playbackQueue.push(decodeRealtimeAudio(base64Audio));\n    this.schedulePlayback();\n  }\n  stopPlayback() {\n    this.playbackQueue = [];\n    for (const source of this.activeSources) {\n      try {\n        source.stop();\n      } catch (e) {\n      }\n    }\n    this.activeSources.clear();\n    if (this.playbackContext != null) {\n      this.playbackTime = this.playbackContext.currentTime;\n    }\n    this.setPlaying(false);\n  }\n  getPlaybackOffsetMs() {\n    const ctx = this.playbackContext;\n    if (ctx == null)\n      return 0;\n    return (ctx.currentTime - this.playbackStartTime) * 1e3;\n  }\n  dispose() {\n    var _a22;\n    this.stopCapture();\n    this.stopPlayback();\n    void ((_a22 = this.playbackContext) == null ? void 0 : _a22.close());\n    this.playbackContext = null;\n  }\n  setPlaying(isPlaying) {\n    var _a22, _b;\n    if (isPlaying && !this.isPlaying) {\n      this.playbackStartTime = (_b = (_a22 = this.playbackContext) == null ? void 0 : _a22.currentTime) != null ? _b : 0;\n    }\n    if (this.isPlaying !== isPlaying) {\n      this.isPlaying = isPlaying;\n      this.onPlayingChange(isPlaying);\n    }\n  }\n  schedulePlayback() {\n    const ctx = this.playbackContext;\n    if (ctx == null || this.playbackQueue.length === 0)\n      return;\n    while (this.playbackQueue.length > 0) {\n      const samples = this.playbackQueue.shift();\n      const buffer = ctx.createBuffer(\n        1,\n        samples.length,\n        this.playbackSampleRate\n      );\n      buffer.getChannelData(0).set(samples);\n      const source = ctx.createBufferSource();\n      source.buffer = buffer;\n      source.connect(ctx.destination);\n      const startTime = Math.max(this.playbackTime, ctx.currentTime);\n      source.start(startTime);\n      this.playbackTime = startTime + buffer.duration;\n      this.activeSources.add(source);\n      this.setPlaying(true);\n      source.onended = () => {\n        this.activeSources.delete(source);\n        if (this.playbackQueue.length === 0 && this.activeSources.size === 0) {\n          this.setPlaying(false);\n        }\n      };\n    }\n  }\n};\n\n// src/realtime/browser-realtime-transport.ts\nimport { safeParseJSON as safeParseJSON5 } from \"@ai-sdk/provider-utils\";\nvar BrowserRealtimeTransport = class {\n  constructor(options) {\n    this.ws = null;\n    this.sendQueue = Promise.resolve();\n    this.model = options.model;\n    this.onServerEvent = options.onServerEvent;\n    this.onError = options.onError;\n    this.onClose = options.onClose;\n  }\n  connect({\n    token,\n    url,\n    onOpen\n  }) {\n    var _a22;\n    (_a22 = this.ws) == null ? void 0 : _a22.close();\n    this.ws = null;\n    const wsConfig = this.model.getWebSocketConfig({ token, url });\n    const ws = new WebSocket(wsConfig.url, wsConfig.protocols);\n    this.ws = ws;\n    ws.onopen = () => {\n      if (this.ws !== ws)\n        return;\n      onOpen();\n    };\n    ws.onmessage = (messageEvent) => {\n      void this.handleMessage(messageEvent);\n    };\n    ws.onerror = () => {\n      this.onError(new Error(\"WebSocket connection error\"));\n    };\n    ws.onclose = () => {\n      if (this.ws === ws) {\n        this.ws = null;\n        this.onClose();\n      }\n    };\n  }\n  disconnect() {\n    var _a22;\n    (_a22 = this.ws) == null ? void 0 : _a22.close();\n    this.ws = null;\n  }\n  sendEvent(event) {\n    this.sendQueue = this.sendQueue.then(async () => {\n      const serialized = await this.model.serializeClientEvent(event);\n      if (serialized != null) {\n        this.sendRaw(serialized);\n      }\n    }).catch((error) => {\n      this.onError(\n        error instanceof Error ? error : new Error(`Failed to send realtime event: ${String(error)}`)\n      );\n    });\n  }\n  sendRaw(data) {\n    var _a22;\n    if (((_a22 = this.ws) == null ? void 0 : _a22.readyState) === WebSocket.OPEN) {\n      this.ws.send(JSON.stringify(data));\n    }\n  }\n  dispose() {\n    this.disconnect();\n  }\n  async handleMessage(messageEvent) {\n    let text2;\n    if (typeof messageEvent.data === \"string\") {\n      text2 = messageEvent.data;\n    } else if (messageEvent.data instanceof Blob) {\n      text2 = await messageEvent.data.text();\n    } else {\n      text2 = new TextDecoder().decode(messageEvent.data);\n    }\n    const parseResult = await safeParseJSON5({ text: text2 });\n    if (!parseResult.success)\n      return;\n    const rawEvent = parseResult.value;\n    if (this.model.getHealthCheckResponse != null) {\n      const autoResponse = this.model.getHealthCheckResponse(rawEvent);\n      if (autoResponse != null) {\n        this.sendRaw(autoResponse);\n      }\n    }\n    const result = this.model.parseServerEvent(rawEvent);\n    const events = Array.isArray(result) ? result : [result];\n    for (const event of events) {\n      await this.onServerEvent(event);\n    }\n  }\n};\n\n// src/realtime/realtime-event-reducer.ts\nimport { safeParseJSON as safeParseJSON6 } from \"@ai-sdk/provider-utils\";\nfunction createInitialRealtimeState() {\n  return {\n    status: \"disconnected\",\n    messages: [],\n    events: [],\n    isCapturing: false,\n    isPlaying: false\n  };\n}\nvar RealtimeEventReducer = class {\n  constructor(maxEvents = 500) {\n    this.maxEvents = maxEvents;\n    this.currentAssistantMessageId = null;\n    this.textAccumulators = /* @__PURE__ */ new Map();\n    this.toolArgAccumulators = /* @__PURE__ */ new Map();\n    this.toolCallIdToMessageId = /* @__PURE__ */ new Map();\n    this.toolCallIdToName = /* @__PURE__ */ new Map();\n    this.inputAudioMessageInsertIndex = /* @__PURE__ */ new Map();\n    this.itemIdToPartLocation = /* @__PURE__ */ new Map();\n  }\n  setStatus(state, status) {\n    return { ...state, status };\n  }\n  setCapturing(state, isCapturing) {\n    return { ...state, isCapturing };\n  }\n  setPlaying(state, isPlaying) {\n    return { ...state, isPlaying };\n  }\n  addUserTextMessage(state, text2) {\n    return {\n      ...state,\n      messages: [\n        ...state.messages,\n        {\n          id: `user-${Date.now()}`,\n          role: \"user\",\n          parts: [{ type: \"text\", text: text2, state: \"done\" }]\n        }\n      ]\n    };\n  }\n  addToolOutput(state, callId, result) {\n    return {\n      state: this.updateToolPartState(state, callId, result),\n      output: {\n        callId,\n        name: this.toolCallIdToName.get(callId),\n        output: JSON.stringify(result)\n      }\n    };\n  }\n  async reduceServerEvent(state, event) {\n    var _a22;\n    let nextState = this.pushEvent(state, event);\n    const effects = [];\n    switch (event.type) {\n      case \"session-created\":\n      case \"session-updated\": {\n        if (nextState.status === \"connecting\") {\n          nextState = this.setStatus(nextState, \"connected\");\n        }\n        break;\n      }\n      case \"audio-delta\": {\n        effects.push({\n          type: \"play-audio\",\n          itemId: event.itemId,\n          delta: event.delta\n        });\n        break;\n      }\n      case \"audio-committed\": {\n        if (event.itemId != null) {\n          this.inputAudioMessageInsertIndex.set(\n            event.itemId,\n            nextState.messages.length\n          );\n        }\n        break;\n      }\n      case \"audio-transcript-delta\":\n      case \"text-delta\": {\n        nextState = this.appendTextDelta(nextState, event.itemId, event.delta);\n        break;\n      }\n      case \"audio-transcript-done\": {\n        nextState = this.finalizeText(\n          nextState,\n          event.itemId,\n          event.transcript\n        );\n        break;\n      }\n      case \"text-done\": {\n        nextState = this.finalizeText(nextState, event.itemId, event.text);\n        break;\n      }\n      case \"input-transcription-completed\": {\n        nextState = this.addInputTranscriptionMessage(\n          nextState,\n          event.itemId,\n          event.transcript\n        );\n        break;\n      }\n      case \"response-created\":\n      case \"response-done\": {\n        this.currentAssistantMessageId = null;\n        break;\n      }\n      case \"speech-started\": {\n        this.currentAssistantMessageId = null;\n        effects.push({ type: \"speech-started\" });\n        break;\n      }\n      case \"function-call-arguments-delta\": {\n        const { state: updatedState, messageId } = this.getOrCreateAssistantMessage(nextState);\n        nextState = updatedState;\n        this.toolCallIdToMessageId.set(event.callId, messageId);\n        const acc = (_a22 = this.toolArgAccumulators.get(event.callId)) != null ? _a22 : \"\";\n        this.toolArgAccumulators.set(event.callId, acc + event.delta);\n        nextState = this.ensureToolPart(nextState, messageId, event.callId);\n        break;\n      }\n      case \"function-call-arguments-done\": {\n        this.toolArgAccumulators.delete(event.callId);\n        this.toolCallIdToName.set(event.callId, event.name);\n        const parseResult = await safeParseJSON6({ text: event.arguments });\n        const parsedInput = parseResult.success ? parseResult.value : {};\n        const messageId = this.toolCallIdToMessageId.get(event.callId);\n        if (messageId != null) {\n          nextState = this.markToolInputAvailable(\n            nextState,\n            messageId,\n            event.callId,\n            event.name,\n            parsedInput\n          );\n        }\n        if (!parseResult.success) {\n          effects.push({\n            type: \"error\",\n            error: new Error(\n              `Failed to parse tool arguments: ${event.arguments}`\n            )\n          });\n        } else {\n          effects.push({\n            type: \"tool-call\",\n            callId: event.callId,\n            name: event.name,\n            args: parsedInput,\n            rawArguments: event.arguments\n          });\n        }\n        break;\n      }\n      case \"error\": {\n        effects.push({ type: \"error\", error: new Error(event.message) });\n        break;\n      }\n    }\n    return { state: nextState, effects };\n  }\n  pushEvent(state, event) {\n    const events = [...state.events, event];\n    return {\n      ...state,\n      events: events.length > this.maxEvents ? events.slice(-this.maxEvents) : events\n    };\n  }\n  getOrCreateAssistantMessage(state) {\n    if (this.currentAssistantMessageId != null) {\n      return { state, messageId: this.currentAssistantMessageId };\n    }\n    const messageId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;\n    this.currentAssistantMessageId = messageId;\n    return {\n      state: {\n        ...state,\n        messages: [\n          ...state.messages,\n          {\n            id: messageId,\n            role: \"assistant\",\n            parts: []\n          }\n        ]\n      },\n      messageId\n    };\n  }\n  addInputTranscriptionMessage(state, itemId, transcript) {\n    var _a22;\n    const messageId = `user-${itemId}`;\n    const existingMessage = state.messages.find(\n      (message) => message.id === messageId\n    );\n    if (existingMessage != null) {\n      return {\n        ...state,\n        messages: state.messages.map(\n          (message) => message.id === messageId ? {\n            ...message,\n            parts: [\n              {\n                type: \"text\",\n                text: transcript,\n                state: \"done\"\n              }\n            ]\n          } : message\n        )\n      };\n    }\n    const insertIndex = Math.min(\n      (_a22 = this.inputAudioMessageInsertIndex.get(itemId)) != null ? _a22 : state.messages.length,\n      state.messages.length\n    );\n    const messages = [...state.messages];\n    messages.splice(insertIndex, 0, {\n      id: messageId,\n      role: \"user\",\n      parts: [\n        {\n          type: \"text\",\n          text: transcript,\n          state: \"done\"\n        }\n      ]\n    });\n    return {\n      ...state,\n      messages\n    };\n  }\n  appendTextDelta(state, itemId, delta) {\n    var _a22;\n    const { state: stateWithMessage, messageId } = this.getOrCreateAssistantMessage(state);\n    const acc = (_a22 = this.textAccumulators.get(itemId)) != null ? _a22 : \"\";\n    const text2 = acc + delta;\n    this.textAccumulators.set(itemId, text2);\n    const location = this.itemIdToPartLocation.get(itemId);\n    if (location != null) {\n      return this.updateMessagePart(\n        stateWithMessage,\n        location.messageId,\n        location.partIndex,\n        { type: \"text\", text: text2, state: \"streaming\" }\n      );\n    }\n    return {\n      ...stateWithMessage,\n      messages: stateWithMessage.messages.map((message) => {\n        if (message.id !== messageId)\n          return message;\n        const partIndex = message.parts.length;\n        this.itemIdToPartLocation.set(itemId, { messageId, partIndex });\n        return {\n          ...message,\n          parts: [\n            ...message.parts,\n            { type: \"text\", text: text2, state: \"streaming\" }\n          ]\n        };\n      })\n    };\n  }\n  finalizeText(state, itemId, finalText) {\n    var _a22;\n    const text2 = (_a22 = finalText != null ? finalText : this.textAccumulators.get(itemId)) != null ? _a22 : \"\";\n    this.textAccumulators.delete(itemId);\n    const location = this.itemIdToPartLocation.get(itemId);\n    if (location == null)\n      return state;\n    this.itemIdToPartLocation.delete(itemId);\n    return this.updateMessagePart(\n      state,\n      location.messageId,\n      location.partIndex,\n      { type: \"text\", text: text2, state: \"done\" }\n    );\n  }\n  ensureToolPart(state, messageId, callId) {\n    return {\n      ...state,\n      messages: state.messages.map((message) => {\n        if (message.id !== messageId)\n          return message;\n        const existingPart = message.parts.find(\n          (part) => part.type === \"dynamic-tool\" && part.toolCallId === callId\n        );\n        if (existingPart != null)\n          return message;\n        return {\n          ...message,\n          parts: [\n            ...message.parts,\n            {\n              type: \"dynamic-tool\",\n              toolName: \"\",\n              toolCallId: callId,\n              state: \"input-streaming\",\n              input: void 0\n            }\n          ]\n        };\n      })\n    };\n  }\n  markToolInputAvailable(state, messageId, callId, name22, input) {\n    return {\n      ...state,\n      messages: state.messages.map((message) => {\n        if (message.id !== messageId)\n          return message;\n        return {\n          ...message,\n          parts: message.parts.map((part) => {\n            if (part.type !== \"dynamic-tool\")\n              return part;\n            const toolPart = part;\n            if (toolPart.toolCallId !== callId)\n              return part;\n            return {\n              ...toolPart,\n              toolName: name22,\n              state: \"input-available\",\n              input\n            };\n          })\n        };\n      })\n    };\n  }\n  updateToolPartState(state, callId, result) {\n    const messageId = this.toolCallIdToMessageId.get(callId);\n    if (messageId == null)\n      return state;\n    return {\n      ...state,\n      messages: state.messages.map((message) => {\n        if (message.id !== messageId)\n          return message;\n        return {\n          ...message,\n          parts: message.parts.map((part) => {\n            if (part.type !== \"dynamic-tool\")\n              return part;\n            const toolPart = part;\n            if (toolPart.toolCallId !== callId)\n              return part;\n            return {\n              ...toolPart,\n              state: \"output-available\",\n              output: result\n            };\n          })\n        };\n      })\n    };\n  }\n  updateMessagePart(state, messageId, partIndex, part) {\n    return {\n      ...state,\n      messages: state.messages.map((message) => {\n        if (message.id !== messageId)\n          return message;\n        const parts = [...message.parts];\n        parts[partIndex] = part;\n        return { ...message, parts };\n      })\n    };\n  }\n};\n\n// src/realtime/realtime-session.ts\nvar AbstractRealtimeSession = class {\n  constructor(options) {\n    this.state = createInitialRealtimeState();\n    this.currentResponseItemId = null;\n    // Tool calls requested by the current (tool-bearing) response, the outputs\n    // that have been submitted for them, and whether that response has finished\n    // delivering its tool calls. Used to request a single response only once\n    // every tool output for the turn has been submitted.\n    this.toolCallsInResponse = /* @__PURE__ */ new Set();\n    this.submittedToolOutputs = /* @__PURE__ */ new Set();\n    this.responseToolCallsClosed = false;\n    var _a22, _b, _c, _d, _e, _f, _g, _h;\n    this.model = options.model;\n    this.api = options.api;\n    this.sessionConfig = options.sessionConfig;\n    this.maxEvents = (_a22 = options.maxEvents) != null ? _a22 : 500;\n    this.reducer = new RealtimeEventReducer(this.maxEvents);\n    this.onToolCall = options.onToolCall;\n    this.onEvent = options.onEvent;\n    this.onError = options.onError;\n    const sampleRate = (_b = options.sampleRate) != null ? _b : 24e3;\n    const captureSampleRate = (_e = (_d = (_c = options.sessionConfig) == null ? void 0 : _c.inputAudioFormat) == null ? void 0 : _d.rate) != null ? _e : sampleRate;\n    const playbackSampleRate = (_h = (_g = (_f = options.sessionConfig) == null ? void 0 : _f.outputAudioFormat) == null ? void 0 : _g.rate) != null ? _h : sampleRate;\n    this.transport = new BrowserRealtimeTransport({\n      model: this.model,\n      onServerEvent: (event) => this.handleServerEvent(event),\n      onError: (error) => {\n        var _a23;\n        this.applyState(this.reducer.setStatus(this.state, \"error\"));\n        (_a23 = this.onError) == null ? void 0 : _a23.call(this, error);\n      },\n      onClose: () => {\n        this.applyState(this.reducer.setStatus(this.state, \"disconnected\"));\n      }\n    });\n    this.audio = new BrowserRealtimeAudio({\n      captureSampleRate,\n      playbackSampleRate,\n      onAudio: (audio) => this.sendAudio(audio),\n      onCapturingChange: (isCapturing) => {\n        this.applyState(this.reducer.setCapturing(this.state, isCapturing));\n      },\n      onPlayingChange: (isPlaying) => {\n        this.applyState(this.reducer.setPlaying(this.state, isPlaying));\n      }\n    });\n  }\n  // ── Connection ─────────────────────────────────────────────────────\n  async connect() {\n    var _a22;\n    this.applyState(this.reducer.setStatus(this.state, \"connecting\"));\n    try {\n      const response = await fetch(this.api.token, {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: JSON.stringify({ sessionConfig: this.sessionConfig })\n      });\n      if (!response.ok) {\n        throw new Error(`Failed to fetch realtime setup: ${response.status}`);\n      }\n      const setupData = await response.json();\n      const { token, url, tools: toolDefinitions } = setupData;\n      const config = {\n        ...this.sessionConfig,\n        tools: toolDefinitions\n      };\n      this.audio.ensurePlaybackContext();\n      this.transport.connect({\n        token,\n        url,\n        onOpen: () => {\n          this.sendEvent({\n            type: \"session-update\",\n            config\n          });\n        }\n      });\n    } catch (error) {\n      this.applyState(this.reducer.setStatus(this.state, \"error\"));\n      (_a22 = this.onError) == null ? void 0 : _a22.call(\n        this,\n        error instanceof Error ? error : new Error(`Connection failed: ${String(error)}`)\n      );\n    }\n  }\n  disconnect() {\n    this.transport.disconnect();\n    this.applyState(this.reducer.setStatus(this.state, \"disconnected\"));\n  }\n  // ── Sending events ─────────────────────────────────────────────────\n  sendEvent(event) {\n    this.transport.sendEvent(event);\n  }\n  sendTextMessage(text2) {\n    this.sendEvent({\n      type: \"conversation-item-create\",\n      item: { type: \"text-message\", role: \"user\", text: text2 }\n    });\n    this.sendEvent({ type: \"response-create\" });\n    this.applyState(this.reducer.addUserTextMessage(this.state, text2));\n  }\n  sendAudio(base64Audio) {\n    this.sendEvent({ type: \"input-audio-append\", audio: base64Audio });\n  }\n  commitAudio() {\n    this.sendEvent({ type: \"input-audio-commit\" });\n  }\n  clearAudioBuffer() {\n    this.sendEvent({ type: \"input-audio-clear\" });\n  }\n  requestResponse(options) {\n    this.sendEvent({\n      type: \"response-create\",\n      ...options != null ? { options } : {}\n    });\n  }\n  cancelResponse() {\n    this.sendEvent({ type: \"response-cancel\" });\n  }\n  // ── Tool output ───────────────────────────────────────────────────\n  addToolOutput(callId, result) {\n    const { state, output } = this.reducer.addToolOutput(\n      this.state,\n      callId,\n      result\n    );\n    this.applyState(state);\n    this.sendEvent({\n      type: \"conversation-item-create\",\n      item: {\n        type: \"function-call-output\",\n        callId: output.callId,\n        name: output.name,\n        output: output.output\n      }\n    });\n    this.submittedToolOutputs.add(callId);\n    this.maybeRequestToolResponse();\n  }\n  /**\n   * Requests a single response once the tool-bearing response has finished\n   * delivering its tool calls and every one of them has an output. Requesting a\n   * response after each individual output can cause the model to continue\n   * without the full tool context on multi-tool turns.\n   */\n  maybeRequestToolResponse() {\n    if (!this.responseToolCallsClosed)\n      return;\n    if (this.toolCallsInResponse.size === 0)\n      return;\n    for (const callId of this.toolCallsInResponse) {\n      if (!this.submittedToolOutputs.has(callId))\n        return;\n    }\n    this.sendEvent({ type: \"response-create\" });\n    this.toolCallsInResponse.clear();\n    this.submittedToolOutputs.clear();\n    this.responseToolCallsClosed = false;\n  }\n  // ── Audio capture ──────────────────────────────────────────────────\n  startAudioCapture(stream) {\n    this.audio.startCapture(stream);\n  }\n  stopAudioCapture() {\n    this.audio.stopCapture();\n  }\n  // ── Playback ───────────────────────────────────────────────────────\n  stopPlayback() {\n    this.audio.stopPlayback();\n  }\n  // ── Cleanup ────────────────────────────────────────────────────────\n  dispose() {\n    this.transport.dispose();\n    this.audio.dispose();\n    this.applyState(\n      this.reducer.setStatus(\n        this.reducer.setPlaying(\n          this.reducer.setCapturing(this.state, false),\n          false\n        ),\n        \"disconnected\"\n      )\n    );\n  }\n  // ── Private helpers ────────────────────────────────────────────────\n  applyState(nextState) {\n    const previousState = this.state;\n    this.state = nextState;\n    if (previousState.status !== nextState.status) {\n      this.setState(\"status\", nextState.status);\n    }\n    if (previousState.messages !== nextState.messages) {\n      this.setState(\"messages\", nextState.messages);\n    }\n    if (previousState.events !== nextState.events) {\n      this.setState(\"events\", nextState.events);\n    }\n    if (previousState.isCapturing !== nextState.isCapturing) {\n      this.setState(\"isCapturing\", nextState.isCapturing);\n    }\n    if (previousState.isPlaying !== nextState.isPlaying) {\n      this.setState(\"isPlaying\", nextState.isPlaying);\n    }\n  }\n  async executeToolCall({\n    name: name22,\n    args,\n    callId\n  }) {\n    var _a22, _b;\n    if (this.onToolCall == null) {\n      (_a22 = this.onError) == null ? void 0 : _a22.call(this, new Error(`No handler provided for tool \"${name22}\"`));\n      return;\n    }\n    try {\n      const result = await this.onToolCall({\n        toolCall: { toolCallId: callId, toolName: name22, args }\n      });\n      if (result !== void 0) {\n        this.addToolOutput(callId, result);\n      }\n    } catch (error) {\n      (_b = this.onError) == null ? void 0 : _b.call(\n        this,\n        error instanceof Error ? error : new Error(`Client tool execution failed: ${String(error)}`)\n      );\n    }\n  }\n  async handleServerEvent(event) {\n    var _a22;\n    const result = await this.reducer.reduceServerEvent(this.state, event);\n    this.applyState(result.state);\n    (_a22 = this.onEvent) == null ? void 0 : _a22.call(this, event);\n    for (const effect of result.effects) {\n      this.handleReducerEffect(effect);\n    }\n    if (event.type === \"response-done\" && this.toolCallsInResponse.size > 0) {\n      this.responseToolCallsClosed = true;\n      this.maybeRequestToolResponse();\n    }\n  }\n  handleReducerEffect(effect) {\n    var _a22;\n    switch (effect.type) {\n      case \"play-audio\": {\n        this.currentResponseItemId = effect.itemId;\n        this.audio.playAudio(effect.delta);\n        break;\n      }\n      case \"speech-started\": {\n        if (this.state.isPlaying) {\n          const playedMs = this.audio.getPlaybackOffsetMs();\n          this.audio.stopPlayback();\n          if (this.currentResponseItemId != null) {\n            this.sendEvent({\n              type: \"conversation-item-truncate\",\n              itemId: this.currentResponseItemId,\n              contentIndex: 0,\n              audioEndMs: Math.round(playedMs)\n            });\n          }\n        }\n        break;\n      }\n      case \"tool-call\": {\n        this.toolCallsInResponse.add(effect.callId);\n        void this.executeToolCall({\n          name: effect.name,\n          args: effect.args,\n          callId: effect.callId\n        });\n        break;\n      }\n      case \"error\": {\n        (_a22 = this.onError) == null ? void 0 : _a22.call(this, effect.error);\n        break;\n      }\n    }\n  }\n};\n\n// src/registry/custom-provider.ts\nimport {\n  NoSuchModelError as NoSuchModelError2\n} from \"@ai-sdk/provider\";\nfunction customProvider({\n  languageModels,\n  embeddingModels,\n  imageModels,\n  transcriptionModels,\n  speechModels,\n  rerankingModels,\n  videoModels,\n  files,\n  skills,\n  fallbackProvider: fallbackProviderArg\n}) {\n  const fallbackProvider = fallbackProviderArg == null ? void 0 : asProviderV4(fallbackProviderArg);\n  const baseProvider = {\n    specificationVersion: \"v4\",\n    languageModel(modelId) {\n      if (languageModels != null && modelId in languageModels) {\n        return resolveLanguageModel(languageModels[modelId]);\n      }\n      if (fallbackProvider) {\n        return fallbackProvider.languageModel(modelId);\n      }\n      throw new NoSuchModelError2({ modelId, modelType: \"languageModel\" });\n    },\n    embeddingModel(modelId) {\n      if (embeddingModels != null && modelId in embeddingModels) {\n        return resolveEmbeddingModel(embeddingModels[modelId]);\n      }\n      if (fallbackProvider) {\n        return fallbackProvider.embeddingModel(modelId);\n      }\n      throw new NoSuchModelError2({ modelId, modelType: \"embeddingModel\" });\n    },\n    imageModel(modelId) {\n      if (imageModels != null && modelId in imageModels) {\n        return resolveImageModel(imageModels[modelId]);\n      }\n      if (fallbackProvider == null ? void 0 : fallbackProvider.imageModel) {\n        return fallbackProvider.imageModel(modelId);\n      }\n      throw new NoSuchModelError2({ modelId, modelType: \"imageModel\" });\n    },\n    transcriptionModel(modelId) {\n      if (transcriptionModels != null && modelId in transcriptionModels) {\n        const model = resolveTranscriptionModel(transcriptionModels[modelId]);\n        if (model != null) {\n          return model;\n        }\n      }\n      if (fallbackProvider == null ? void 0 : fallbackProvider.transcriptionModel) {\n        return fallbackProvider.transcriptionModel(modelId);\n      }\n      throw new NoSuchModelError2({ modelId, modelType: \"transcriptionModel\" });\n    },\n    speechModel(modelId) {\n      if (speechModels != null && modelId in speechModels) {\n        const model = resolveSpeechModel(speechModels[modelId]);\n        if (model != null) {\n          return model;\n        }\n      }\n      if (fallbackProvider == null ? void 0 : fallbackProvider.speechModel) {\n        return fallbackProvider.speechModel(modelId);\n      }\n      throw new NoSuchModelError2({ modelId, modelType: \"speechModel\" });\n    },\n    rerankingModel(modelId) {\n      if (rerankingModels != null && modelId in rerankingModels) {\n        return resolveRerankingModel(rerankingModels[modelId]);\n      }\n      if (fallbackProvider == null ? void 0 : fallbackProvider.rerankingModel) {\n        return fallbackProvider.rerankingModel(modelId);\n      }\n      throw new NoSuchModelError2({ modelId, modelType: \"rerankingModel\" });\n    },\n    videoModel(modelId) {\n      if (videoModels != null && modelId in videoModels) {\n        return resolveVideoModel(videoModels[modelId]);\n      }\n      const videoModel = fallbackProvider == null ? void 0 : fallbackProvider.videoModel;\n      if (videoModel) {\n        return videoModel(modelId);\n      }\n      throw new NoSuchModelError2({ modelId, modelType: \"videoModel\" });\n    }\n  };\n  const filesAndSkills = {\n    ...files != null || (fallbackProvider == null ? void 0 : fallbackProvider.files) != null ? {\n      files() {\n        return files != null ? files : fallbackProvider.files();\n      }\n    } : {},\n    ...skills != null || (fallbackProvider == null ? void 0 : fallbackProvider.skills) != null ? {\n      skills() {\n        return skills != null ? skills : fallbackProvider.skills();\n      }\n    } : {}\n  };\n  return Object.assign(baseProvider, filesAndSkills);\n}\n\n// src/registry/no-such-provider-error.ts\nimport { AISDKError as AISDKError24, NoSuchModelError as NoSuchModelError3 } from \"@ai-sdk/provider\";\nvar name21 = \"AI_NoSuchProviderError\";\nvar marker21 = `vercel.ai.error.${name21}`;\nvar symbol21 = Symbol.for(marker21);\nvar _a21;\nvar NoSuchProviderError = class extends NoSuchModelError3 {\n  constructor({\n    modelId,\n    modelType,\n    providerId,\n    availableProviders,\n    message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`\n  }) {\n    super({ errorName: name21, modelId, modelType, message });\n    this[_a21] = true;\n    this.providerId = providerId;\n    this.availableProviders = availableProviders;\n  }\n  static isInstance(error) {\n    return AISDKError24.hasMarker(error, marker21);\n  }\n};\n_a21 = symbol21;\n\n// src/registry/provider-registry.ts\nimport {\n  NoSuchModelError as NoSuchModelError4\n} from \"@ai-sdk/provider\";\nfunction createProviderRegistry(providers, {\n  separator = \":\",\n  languageModelMiddleware,\n  imageModelMiddleware\n} = {}) {\n  const registry = new DefaultProviderRegistry({\n    separator,\n    languageModelMiddleware,\n    imageModelMiddleware\n  });\n  for (const [id, provider] of Object.entries(providers)) {\n    registry.registerProvider({ id, provider });\n  }\n  return registry;\n}\nvar experimental_createProviderRegistry = createProviderRegistry;\nvar DefaultProviderRegistry = class {\n  constructor({\n    separator,\n    languageModelMiddleware,\n    imageModelMiddleware\n  }) {\n    this.providers = {};\n    this.separator = separator;\n    this.languageModelMiddleware = languageModelMiddleware;\n    this.imageModelMiddleware = imageModelMiddleware;\n  }\n  registerProvider({\n    id,\n    provider\n  }) {\n    var _a22;\n    const providerV4 = asProviderV4(provider);\n    const videoModel = (_a22 = provider.videoModel) == null ? void 0 : _a22.bind(provider);\n    this.providers[id] = videoModel == null ? providerV4 : Object.assign(Object.create(Object.getPrototypeOf(providerV4)), {\n      ...providerV4,\n      videoModel: (modelId) => asVideoModelV4(videoModel(modelId))\n    });\n  }\n  getProvider(id, modelType) {\n    const provider = this.providers[id];\n    if (provider == null) {\n      throw new NoSuchProviderError({\n        modelId: id,\n        modelType,\n        providerId: id,\n        availableProviders: Object.keys(this.providers)\n      });\n    }\n    return provider;\n  }\n  splitId(id, modelType) {\n    const index = id.indexOf(this.separator);\n    if (index === -1) {\n      throw new NoSuchModelError4({\n        modelId: id,\n        modelType,\n        message: `Invalid ${modelType} id for registry: ${id} (must be in the format \"providerId${this.separator}modelId\")`\n      });\n    }\n    return [id.slice(0, index), id.slice(index + this.separator.length)];\n  }\n  languageModel(id) {\n    var _a22, _b;\n    const [providerId, modelId] = this.splitId(id, \"languageModel\");\n    let model = (_b = (_a22 = this.getProvider(providerId, \"languageModel\")).languageModel) == null ? void 0 : _b.call(\n      _a22,\n      modelId\n    );\n    if (model == null) {\n      throw new NoSuchModelError4({ modelId: id, modelType: \"languageModel\" });\n    }\n    if (this.languageModelMiddleware != null) {\n      model = wrapLanguageModel({\n        model,\n        middleware: this.languageModelMiddleware\n      });\n    }\n    return model;\n  }\n  embeddingModel(id) {\n    var _a22;\n    const [providerId, modelId] = this.splitId(id, \"embeddingModel\");\n    const provider = this.getProvider(providerId, \"embeddingModel\");\n    const model = (_a22 = provider.embeddingModel) == null ? void 0 : _a22.call(provider, modelId);\n    if (model == null) {\n      throw new NoSuchModelError4({\n        modelId: id,\n        modelType: \"embeddingModel\"\n      });\n    }\n    return model;\n  }\n  imageModel(id) {\n    var _a22;\n    const [providerId, modelId] = this.splitId(id, \"imageModel\");\n    const provider = this.getProvider(providerId, \"imageModel\");\n    let model = (_a22 = provider.imageModel) == null ? void 0 : _a22.call(provider, modelId);\n    if (model == null) {\n      throw new NoSuchModelError4({ modelId: id, modelType: \"imageModel\" });\n    }\n    if (this.imageModelMiddleware != null) {\n      model = wrapImageModel({\n        model,\n        middleware: this.imageModelMiddleware\n      });\n    }\n    return model;\n  }\n  transcriptionModel(id) {\n    var _a22;\n    const [providerId, modelId] = this.splitId(id, \"transcriptionModel\");\n    const provider = this.getProvider(providerId, \"transcriptionModel\");\n    const model = (_a22 = provider.transcriptionModel) == null ? void 0 : _a22.call(provider, modelId);\n    if (model == null) {\n      throw new NoSuchModelError4({\n        modelId: id,\n        modelType: \"transcriptionModel\"\n      });\n    }\n    return model;\n  }\n  speechModel(id) {\n    var _a22;\n    const [providerId, modelId] = this.splitId(id, \"speechModel\");\n    const provider = this.getProvider(providerId, \"speechModel\");\n    const model = (_a22 = provider.speechModel) == null ? void 0 : _a22.call(provider, modelId);\n    if (model == null) {\n      throw new NoSuchModelError4({ modelId: id, modelType: \"speechModel\" });\n    }\n    return model;\n  }\n  rerankingModel(id) {\n    var _a22;\n    const [providerId, modelId] = this.splitId(id, \"rerankingModel\");\n    const provider = this.getProvider(providerId, \"rerankingModel\");\n    const model = (_a22 = provider.rerankingModel) == null ? void 0 : _a22.call(provider, modelId);\n    if (model == null) {\n      throw new NoSuchModelError4({ modelId: id, modelType: \"rerankingModel\" });\n    }\n    return model;\n  }\n  videoModel(id) {\n    var _a22;\n    const [providerId, modelId] = this.splitId(id, \"videoModel\");\n    const provider = this.getProvider(providerId, \"videoModel\");\n    const model = (_a22 = provider.videoModel) == null ? void 0 : _a22.call(provider, modelId);\n    if (model == null) {\n      throw new NoSuchModelError4({ modelId: id, modelType: \"videoModel\" });\n    }\n    return asVideoModelV4(model);\n  }\n  files(id) {\n    var _a22;\n    const provider = this.getProvider(id, \"languageModel\");\n    const files = (_a22 = provider.files) == null ? void 0 : _a22.call(provider);\n    if (files == null) {\n      throw new Error(\n        `The provider \"${id}\" does not support file uploads. Make sure it exposes a files() method.`\n      );\n    }\n    return files;\n  }\n  skills(id) {\n    var _a22;\n    const provider = this.getProvider(id, \"languageModel\");\n    const skills = (_a22 = provider.skills) == null ? void 0 : _a22.call(provider);\n    if (skills == null) {\n      throw new Error(\n        `The provider \"${id}\" does not support skills. Make sure it exposes a skills() method.`\n      );\n    }\n    return skills;\n  }\n};\n\n// src/rerank/rerank.ts\nimport {\n  createIdGenerator as createIdGenerator8\n} from \"@ai-sdk/provider-utils\";\nvar originalGenerateCallId6 = createIdGenerator8({\n  prefix: \"call\",\n  size: 24\n});\nasync function rerank({\n  model: modelArg,\n  documents,\n  query,\n  topN,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  providerOptions,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  onStart,\n  experimental_onStart,\n  onEnd,\n  experimental_onEnd,\n  _internal: { generateCallId = originalGenerateCallId6 } = {}\n}) {\n  var _a22;\n  const model = resolveRerankingModel(modelArg);\n  const callId = generateCallId();\n  const resolvedOnStart = onStart != null ? onStart : experimental_onStart;\n  const resolvedOnEnd = onEnd != null ? onEnd : experimental_onEnd;\n  const telemetryDispatcher = createTelemetryDispatcher({\n    telemetry\n  });\n  const runInTracingChannelSpan = (_a22 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a22 : async ({ execute }) => await execute();\n  if (documents.length === 0) {\n    await notify({\n      event: {\n        callId,\n        operationId: \"ai.rerank\",\n        provider: model.provider,\n        modelId: model.modelId,\n        documents,\n        query,\n        topN,\n        maxRetries: maxRetriesArg != null ? maxRetriesArg : 2,\n        headers,\n        providerOptions\n      },\n      callbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n    });\n    await notify({\n      event: {\n        callId,\n        operationId: \"ai.rerank\",\n        provider: model.provider,\n        modelId: model.modelId,\n        documents,\n        query,\n        ranking: [],\n        warnings: [],\n        providerMetadata: void 0,\n        response: {\n          timestamp: /* @__PURE__ */ new Date(),\n          modelId: model.modelId\n        }\n      },\n      callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n    });\n    return new DefaultRerankResult({\n      originalDocuments: [],\n      ranking: [],\n      providerMetadata: void 0,\n      response: {\n        timestamp: /* @__PURE__ */ new Date(),\n        modelId: model.modelId\n      }\n    });\n  }\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const documentsToSend = typeof documents[0] === \"string\" ? { type: \"text\", values: documents } : { type: \"object\", values: documents };\n  const startEvent = {\n    callId,\n    operationId: \"ai.rerank\",\n    provider: model.provider,\n    modelId: model.modelId,\n    documents,\n    query,\n    topN,\n    maxRetries,\n    headers,\n    providerOptions\n  };\n  return await runInTracingChannelSpan({\n    type: \"rerank\",\n    event: startEvent,\n    execute: async () => {\n      var _a23, _b, _c, _d, _e;\n      await notify({\n        event: startEvent,\n        callbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n      });\n      try {\n        const { ranking, response, providerMetadata, warnings } = await retry(\n          async () => {\n            await notify({\n              event: {\n                callId,\n                operationId: \"ai.rerank.doRerank\",\n                provider: model.provider,\n                modelId: model.modelId,\n                documents,\n                documentsType: documentsToSend.type,\n                query,\n                topN\n              },\n              callbacks: [telemetryDispatcher.onRerankStart]\n            });\n            const modelResponse = await model.doRerank({\n              documents: documentsToSend,\n              query,\n              topN,\n              providerOptions,\n              abortSignal,\n              headers\n            });\n            const ranking2 = modelResponse.ranking;\n            await notify({\n              event: {\n                callId,\n                operationId: \"ai.rerank.doRerank\",\n                provider: model.provider,\n                modelId: model.modelId,\n                documentsType: documentsToSend.type,\n                ranking: ranking2\n              },\n              callbacks: [telemetryDispatcher.onRerankEnd]\n            });\n            return {\n              ranking: ranking2,\n              providerMetadata: modelResponse.providerMetadata,\n              response: modelResponse.response,\n              warnings: modelResponse.warnings\n            };\n          }\n        );\n        logWarnings({\n          warnings: warnings != null ? warnings : [],\n          provider: model.provider,\n          model: model.modelId\n        });\n        await notify({\n          event: {\n            callId,\n            operationId: \"ai.rerank\",\n            provider: model.provider,\n            modelId: model.modelId,\n            documents,\n            query,\n            ranking: ranking.map((r) => ({\n              originalIndex: r.index,\n              score: r.relevanceScore,\n              document: documents[r.index]\n            })),\n            warnings: warnings != null ? warnings : [],\n            providerMetadata,\n            response: {\n              id: response == null ? void 0 : response.id,\n              timestamp: (_a23 = response == null ? void 0 : response.timestamp) != null ? _a23 : /* @__PURE__ */ new Date(),\n              modelId: (_b = response == null ? void 0 : response.modelId) != null ? _b : model.modelId,\n              headers: response == null ? void 0 : response.headers,\n              body: response == null ? void 0 : response.body\n            }\n          },\n          callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n        });\n        return new DefaultRerankResult({\n          originalDocuments: documents,\n          ranking: ranking.map((ranking2) => ({\n            originalIndex: ranking2.index,\n            score: ranking2.relevanceScore,\n            document: documents[ranking2.index]\n          })),\n          providerMetadata,\n          response: {\n            id: response == null ? void 0 : response.id,\n            timestamp: (_c = response == null ? void 0 : response.timestamp) != null ? _c : /* @__PURE__ */ new Date(),\n            modelId: (_d = response == null ? void 0 : response.modelId) != null ? _d : model.modelId,\n            headers: response == null ? void 0 : response.headers,\n            body: response == null ? void 0 : response.body\n          }\n        });\n      } catch (error) {\n        await ((_e = telemetryDispatcher.onError) == null ? void 0 : _e.call(telemetryDispatcher, { callId, error }));\n        throw error;\n      }\n    }\n  });\n}\nvar DefaultRerankResult = class {\n  constructor(options) {\n    this.originalDocuments = options.originalDocuments;\n    this.ranking = options.ranking;\n    this.response = options.response;\n    this.providerMetadata = options.providerMetadata;\n  }\n  get rerankedDocuments() {\n    return this.ranking.map((ranking) => ranking.document);\n  }\n};\n\n// src/transcribe/transcribe.ts\nimport {\n  detectMediaType as detectMediaType5,\n  withUserAgentSuffix as withUserAgentSuffix10\n} from \"@ai-sdk/provider-utils\";\nvar defaultDownload2 = createDownload();\nasync function transcribe({\n  model,\n  audio,\n  providerOptions = {},\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  download: downloadFn = defaultDownload2\n}) {\n  const resolvedModel = resolveTranscriptionModel(model);\n  if (!resolvedModel) {\n    throw new Error(\"Model could not be resolved\");\n  }\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal\n  });\n  const headersWithUserAgent = withUserAgentSuffix10(\n    headers != null ? headers : {},\n    `ai/${VERSION}`\n  );\n  const audioData = audio instanceof URL ? (await downloadFn({ url: audio, abortSignal })).data : convertDataContentToUint8Array(audio);\n  const result = await retry(\n    () => {\n      var _a22;\n      return resolvedModel.doGenerate({\n        audio: audioData,\n        abortSignal,\n        headers: headersWithUserAgent,\n        providerOptions,\n        mediaType: (_a22 = detectMediaType5({\n          data: audioData,\n          topLevelType: \"audio\"\n        })) != null ? _a22 : \"audio/wav\"\n      });\n    }\n  );\n  logWarnings({\n    warnings: result.warnings,\n    provider: resolvedModel.provider,\n    model: resolvedModel.modelId\n  });\n  if (!result.text) {\n    throw new NoTranscriptGeneratedError({ responses: [result.response] });\n  }\n  return new DefaultTranscriptionResult({\n    text: result.text,\n    segments: result.segments,\n    language: result.language,\n    durationInSeconds: result.durationInSeconds,\n    warnings: result.warnings,\n    responses: [result.response],\n    providerMetadata: result.providerMetadata\n  });\n}\nvar DefaultTranscriptionResult = class {\n  constructor(options) {\n    var _a22;\n    this.text = options.text;\n    this.segments = options.segments;\n    this.language = options.language;\n    this.durationInSeconds = options.durationInSeconds;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = (_a22 = options.providerMetadata) != null ? _a22 : {};\n  }\n};\n\n// src/transcribe/index.ts\nvar experimental_transcribe = transcribe;\n\n// src/ui/call-completion-api.ts\nimport {\n  parseJsonEventStream,\n  withUserAgentSuffix as withUserAgentSuffix11,\n  getRuntimeEnvironmentUserAgent as getRuntimeEnvironmentUserAgent2\n} from \"@ai-sdk/provider-utils\";\n\n// src/ui/process-text-stream.ts\nasync function processTextStream({\n  stream,\n  onTextPart\n}) {\n  const reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n  while (true) {\n    const { done, value } = await reader.read();\n    if (done) {\n      break;\n    }\n    await onTextPart(value);\n  }\n}\n\n// src/ui/call-completion-api.ts\nvar getOriginalFetch = () => fetch;\nasync function callCompletionApi({\n  api,\n  prompt,\n  credentials,\n  headers,\n  body,\n  streamProtocol = \"data\",\n  setCompletion,\n  setLoading,\n  setError,\n  setAbortController,\n  onFinish,\n  onError,\n  fetch: fetch2 = getOriginalFetch()\n}) {\n  var _a22;\n  try {\n    setLoading(true);\n    setError(void 0);\n    const abortController = new AbortController();\n    setAbortController(abortController);\n    setCompletion(\"\");\n    const response = await fetch2(api, {\n      method: \"POST\",\n      body: JSON.stringify({\n        prompt,\n        ...body\n      }),\n      credentials,\n      headers: withUserAgentSuffix11(\n        {\n          \"Content-Type\": \"application/json\",\n          ...headers\n        },\n        `ai-sdk/${VERSION}`,\n        getRuntimeEnvironmentUserAgent2()\n      ),\n      signal: abortController.signal\n    }).catch((err) => {\n      throw err;\n    });\n    if (!response.ok) {\n      throw new Error(\n        (_a22 = await response.text()) != null ? _a22 : \"Failed to fetch the chat response.\"\n      );\n    }\n    if (!response.body) {\n      throw new Error(\"The response body is empty.\");\n    }\n    let result = \"\";\n    switch (streamProtocol) {\n      case \"text\": {\n        await processTextStream({\n          stream: response.body,\n          onTextPart: (chunk) => {\n            result += chunk;\n            setCompletion(result);\n          }\n        });\n        break;\n      }\n      case \"data\": {\n        await consumeStream({\n          stream: parseJsonEventStream({\n            stream: response.body,\n            schema: uiMessageChunkSchema\n          }).pipeThrough(\n            new TransformStream({\n              async transform(part) {\n                if (!part.success) {\n                  throw part.error;\n                }\n                const streamPart = part.value;\n                if (streamPart.type === \"text-delta\") {\n                  result += streamPart.delta;\n                  setCompletion(result);\n                } else if (streamPart.type === \"error\") {\n                  throw new Error(streamPart.errorText);\n                }\n              }\n            })\n          ),\n          onError: (error) => {\n            throw error;\n          }\n        });\n        break;\n      }\n      default: {\n        const exhaustiveCheck = streamProtocol;\n        throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);\n      }\n    }\n    if (onFinish) {\n      onFinish(prompt, result);\n    }\n    setAbortController(null);\n    return result;\n  } catch (err) {\n    if (err.name === \"AbortError\") {\n      setAbortController(null);\n      return null;\n    }\n    if (err instanceof Error) {\n      if (onError) {\n        onError(err);\n      }\n    }\n    setError(err);\n  } finally {\n    setLoading(false);\n  }\n}\n\n// src/ui/chat.ts\nimport {\n  generateId as generateIdFunc2\n} from \"@ai-sdk/provider-utils\";\n\n// src/ui/convert-file-list-to-file-ui-parts.ts\nasync function convertFileListToFileUIParts(files) {\n  if (files == null) {\n    return [];\n  }\n  if (!globalThis.FileList || !(files instanceof globalThis.FileList)) {\n    throw new Error(\"FileList is not supported in the current environment\");\n  }\n  return Promise.all(\n    Array.from(files).map(async (file) => {\n      const { name: name22, type } = file;\n      const dataUrl = await new Promise((resolve3, reject) => {\n        const reader = new FileReader();\n        reader.onload = (readerEvent) => {\n          var _a22;\n          resolve3((_a22 = readerEvent.target) == null ? void 0 : _a22.result);\n        };\n        reader.onerror = (error) => reject(error);\n        reader.readAsDataURL(file);\n      });\n      return {\n        type: \"file\",\n        mediaType: type,\n        filename: name22,\n        url: dataUrl\n      };\n    })\n  );\n}\n\n// src/ui/default-chat-transport.ts\nimport { parseJsonEventStream as parseJsonEventStream2 } from \"@ai-sdk/provider-utils\";\n\n// src/ui/http-chat-transport.ts\nimport {\n  normalizeHeaders,\n  resolve as resolve2\n} from \"@ai-sdk/provider-utils\";\nvar HttpChatTransport = class {\n  constructor({\n    api = \"/api/chat\",\n    credentials,\n    headers,\n    body,\n    fetch: fetch2,\n    prepareSendMessagesRequest,\n    prepareReconnectToStreamRequest\n  }) {\n    this.api = api;\n    this.credentials = credentials;\n    this.headers = headers;\n    this.body = body;\n    this.fetch = fetch2;\n    this.prepareSendMessagesRequest = prepareSendMessagesRequest;\n    this.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n  }\n  async sendMessages({\n    abortSignal,\n    ...options\n  }) {\n    var _a22, _b, _c, _d, _e;\n    const resolvedBody = await resolve2(this.body);\n    const resolvedHeaders = await resolve2(this.headers);\n    const resolvedCredentials = await resolve2(this.credentials);\n    const baseHeaders = {\n      ...normalizeHeaders(resolvedHeaders),\n      ...normalizeHeaders(options.headers)\n    };\n    const preparedRequest = await ((_a22 = this.prepareSendMessagesRequest) == null ? void 0 : _a22.call(this, {\n      api: this.api,\n      id: options.chatId,\n      messages: options.messages,\n      body: { ...resolvedBody, ...options.body },\n      headers: baseHeaders,\n      credentials: resolvedCredentials,\n      requestMetadata: options.metadata,\n      trigger: options.trigger,\n      messageId: options.messageId\n    }));\n    const api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : this.api;\n    const headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n    const body = (preparedRequest == null ? void 0 : preparedRequest.body) !== void 0 ? preparedRequest.body : {\n      ...resolvedBody,\n      ...options.body,\n      id: options.chatId,\n      messages: options.messages,\n      trigger: options.trigger,\n      messageId: options.messageId\n    };\n    const credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n    const fetch2 = (_d = this.fetch) != null ? _d : globalThis.fetch;\n    const response = await fetch2(api, {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n        ...headers\n      },\n      body: JSON.stringify(body),\n      credentials,\n      signal: abortSignal\n    });\n    if (!response.ok) {\n      throw new Error(\n        (_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\"\n      );\n    }\n    if (!response.body) {\n      throw new Error(\"The response body is empty.\");\n    }\n    return this.processResponseStream(response.body);\n  }\n  async reconnectToStream(options) {\n    var _a22, _b, _c, _d, _e;\n    const resolvedBody = await resolve2(this.body);\n    const resolvedHeaders = await resolve2(this.headers);\n    const resolvedCredentials = await resolve2(this.credentials);\n    const baseHeaders = {\n      ...normalizeHeaders(resolvedHeaders),\n      ...normalizeHeaders(options.headers)\n    };\n    const preparedRequest = await ((_a22 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a22.call(this, {\n      api: this.api,\n      id: options.chatId,\n      body: { ...resolvedBody, ...options.body },\n      headers: baseHeaders,\n      credentials: resolvedCredentials,\n      requestMetadata: options.metadata\n    }));\n    const api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : `${this.api}/${options.chatId}/stream`;\n    const headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n    const credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n    const fetch2 = (_d = this.fetch) != null ? _d : globalThis.fetch;\n    const response = await fetch2(api, {\n      method: \"GET\",\n      headers,\n      credentials\n    });\n    if (response.status === 204) {\n      return null;\n    }\n    if (!response.ok) {\n      throw new Error(\n        (_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\"\n      );\n    }\n    if (!response.body) {\n      throw new Error(\"The response body is empty.\");\n    }\n    return this.processResponseStream(response.body);\n  }\n};\n\n// src/ui/default-chat-transport.ts\nvar DefaultChatTransport = class extends HttpChatTransport {\n  constructor(options = {}) {\n    super(options);\n  }\n  processResponseStream(stream) {\n    return parseJsonEventStream2({\n      stream,\n      schema: uiMessageChunkSchema\n    }).pipeThrough(\n      new TransformStream({\n        async transform(chunk, controller) {\n          if (!chunk.success) {\n            throw chunk.error;\n          }\n          controller.enqueue(chunk.value);\n        }\n      })\n    );\n  }\n};\n\n// src/ui/chat.ts\nvar AbstractChat = class {\n  constructor({\n    generateId: generateId2 = generateIdFunc2,\n    id = generateId2(),\n    transport = new DefaultChatTransport(),\n    messageMetadataSchema,\n    dataPartSchemas,\n    state,\n    onError,\n    onToolCall,\n    onFinish,\n    onData,\n    sendAutomaticallyWhen\n  }) {\n    this.activeResponse = void 0;\n    this.jobExecutor = new SerialJobExecutor();\n    /**\n     * Appends or replaces a user message to the chat list. This triggers the API call to fetch\n     * the assistant's response.\n     *\n     * If a messageId is provided, the message will be replaced.\n     */\n    this.sendMessage = async (message, options) => {\n      var _a22, _b, _c, _d;\n      if (message == null) {\n        await this.makeRequest({\n          trigger: \"submit-message\",\n          messageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,\n          ...options\n        });\n        return;\n      }\n      let uiMessage;\n      if (\"text\" in message || \"files\" in message) {\n        const fileParts = Array.isArray(message.files) ? message.files : await convertFileListToFileUIParts(message.files);\n        uiMessage = {\n          parts: [\n            ...fileParts,\n            ...\"text\" in message && message.text != null ? [{ type: \"text\", text: message.text }] : []\n          ]\n        };\n      } else {\n        uiMessage = message;\n      }\n      if (message.messageId != null) {\n        const messageIndex = this.state.messages.findIndex(\n          (m) => m.id === message.messageId\n        );\n        if (messageIndex === -1) {\n          throw new Error(`message with id ${message.messageId} not found`);\n        }\n        if (this.state.messages[messageIndex].role !== \"user\") {\n          throw new Error(\n            `message with id ${message.messageId} is not a user message`\n          );\n        }\n        this.state.messages = this.state.messages.slice(0, messageIndex + 1);\n        this.state.replaceMessage(messageIndex, {\n          ...uiMessage,\n          id: message.messageId,\n          role: (_b = uiMessage.role) != null ? _b : \"user\",\n          metadata: message.metadata\n        });\n      } else {\n        this.state.pushMessage({\n          ...uiMessage,\n          id: (_c = uiMessage.id) != null ? _c : this.generateId(),\n          role: (_d = uiMessage.role) != null ? _d : \"user\",\n          metadata: message.metadata\n        });\n      }\n      await this.makeRequest({\n        trigger: \"submit-message\",\n        messageId: message.messageId,\n        ...options\n      });\n    };\n    /**\n     * Regenerate the assistant message with the provided message id.\n     * If no message id is provided, the last assistant message will be regenerated.\n     */\n    this.regenerate = async ({\n      messageId,\n      ...options\n    } = {}) => {\n      const messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);\n      if (messageIndex === -1) {\n        throw new Error(`message ${messageId} not found`);\n      }\n      this.state.messages = this.state.messages.slice(\n        0,\n        // if the message is a user message, we need to include it in the request:\n        this.messages[messageIndex].role === \"assistant\" ? messageIndex : messageIndex + 1\n      );\n      await this.makeRequest({\n        trigger: \"regenerate-message\",\n        messageId,\n        ...options\n      });\n    };\n    /**\n     * Attempt to resume an ongoing streaming response.\n     */\n    this.resumeStream = async (options = {}) => {\n      await this.makeRequest({ trigger: \"resume-stream\", ...options });\n    };\n    /**\n     * Clear the error state and set the status to ready if the chat is in an error state.\n     */\n    this.clearError = () => {\n      if (this.status === \"error\") {\n        this.state.error = void 0;\n        this.setStatus({ status: \"ready\" });\n      }\n    };\n    this.addToolApprovalResponse = async ({\n      id,\n      approved,\n      reason,\n      options\n    }) => this.jobExecutor.run(async () => {\n      const messages = this.state.messages;\n      const lastMessage = messages[messages.length - 1];\n      const updatePart = (part) => isToolUIPart(part) && part.state === \"approval-requested\" && part.approval.id === id ? {\n        ...part,\n        state: \"approval-responded\",\n        approval: { id, approved, reason }\n      } : part;\n      this.state.replaceMessage(messages.length - 1, {\n        ...lastMessage,\n        parts: lastMessage.parts.map(updatePart)\n      });\n      if (this.activeResponse) {\n        this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n      }\n      if (this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n        this.shouldSendAutomatically().then((shouldSend) => {\n          var _a22;\n          if (shouldSend) {\n            this.makeRequest({\n              trigger: \"submit-message\",\n              messageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,\n              ...options\n            });\n          }\n        });\n      }\n    });\n    this.addToolOutput = async ({\n      state = \"output-available\",\n      toolCallId,\n      output,\n      errorText,\n      options\n    }) => this.jobExecutor.run(async () => {\n      const messages = this.state.messages;\n      const lastMessage = messages[messages.length - 1];\n      const updatePart = (part) => isToolUIPart(part) && part.toolCallId === toolCallId ? { ...part, state, output, errorText } : part;\n      this.state.replaceMessage(messages.length - 1, {\n        ...lastMessage,\n        parts: lastMessage.parts.map(updatePart)\n      });\n      if (this.activeResponse) {\n        this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n      }\n      if (this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n        this.shouldSendAutomatically().then((shouldSend) => {\n          var _a22;\n          if (shouldSend) {\n            this.makeRequest({\n              trigger: \"submit-message\",\n              messageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,\n              ...options\n            });\n          }\n        });\n      }\n    });\n    /** @deprecated Use addToolOutput */\n    this.addToolResult = this.addToolOutput;\n    /**\n     * Abort the current request immediately, keep the generated tokens if any.\n     */\n    this.stop = async () => {\n      var _a22;\n      if (this.status !== \"streaming\" && this.status !== \"submitted\")\n        return;\n      if ((_a22 = this.activeResponse) == null ? void 0 : _a22.abortController) {\n        this.activeResponse.abortController.abort();\n      }\n    };\n    this.id = id;\n    this.transport = transport;\n    this.generateId = generateId2;\n    this.messageMetadataSchema = messageMetadataSchema;\n    this.dataPartSchemas = dataPartSchemas;\n    this.state = state;\n    this.onError = onError;\n    this.onToolCall = onToolCall;\n    this.onFinish = onFinish;\n    this.onData = onData;\n    this.sendAutomaticallyWhen = sendAutomaticallyWhen;\n  }\n  /**\n   * Hook status:\n   *\n   * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n   * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n   * - `ready`: The full response has been received and processed; a new user message can be submitted.\n   * - `error`: An error occurred during the API request, preventing successful completion.\n   */\n  get status() {\n    return this.state.status;\n  }\n  setStatus({\n    status,\n    error\n  }) {\n    if (this.status === status)\n      return;\n    this.state.status = status;\n    this.state.error = error;\n  }\n  get error() {\n    return this.state.error;\n  }\n  get messages() {\n    return this.state.messages;\n  }\n  get lastMessage() {\n    return this.state.messages[this.state.messages.length - 1];\n  }\n  set messages(messages) {\n    this.state.messages = messages;\n  }\n  async shouldSendAutomatically() {\n    if (!this.sendAutomaticallyWhen)\n      return false;\n    const result = this.sendAutomaticallyWhen({\n      messages: this.state.messages\n    });\n    if (result && typeof result === \"object\" && \"then\" in result) {\n      return await result;\n    }\n    return result;\n  }\n  async makeRequest({\n    trigger,\n    metadata,\n    headers,\n    body,\n    messageId\n  }) {\n    var _a22, _b, _c;\n    let resumeStream;\n    if (trigger === \"resume-stream\") {\n      try {\n        const reconnect = await this.transport.reconnectToStream({\n          chatId: this.id,\n          metadata,\n          headers,\n          body\n        });\n        if (reconnect == null) {\n          return;\n        }\n        resumeStream = reconnect;\n      } catch (err) {\n        if (this.onError && err instanceof Error) {\n          this.onError(err);\n        }\n        this.setStatus({ status: \"error\", error: err });\n        return;\n      }\n    }\n    this.setStatus({ status: \"submitted\", error: void 0 });\n    const lastMessage = this.lastMessage;\n    let isAbort = false;\n    let isDisconnect = false;\n    let isError = false;\n    try {\n      const activeResponse = {\n        state: createStreamingUIMessageState({\n          lastMessage: this.state.snapshot(lastMessage),\n          messageId: this.generateId()\n        }),\n        abortController: new AbortController()\n      };\n      activeResponse.abortController.signal.addEventListener(\"abort\", () => {\n        isAbort = true;\n      });\n      this.activeResponse = activeResponse;\n      let stream;\n      if (trigger === \"resume-stream\") {\n        stream = resumeStream;\n      } else {\n        stream = await this.transport.sendMessages({\n          chatId: this.id,\n          messages: this.state.messages,\n          abortSignal: activeResponse.abortController.signal,\n          metadata,\n          headers,\n          body,\n          trigger,\n          messageId\n        });\n      }\n      const runUpdateMessageJob = (job) => (\n        // serialize the job execution to avoid race conditions:\n        this.jobExecutor.run(\n          () => job({\n            state: activeResponse.state,\n            write: () => {\n              var _a23;\n              this.setStatus({ status: \"streaming\" });\n              const replaceLastMessage = activeResponse.state.message.id === ((_a23 = this.lastMessage) == null ? void 0 : _a23.id);\n              if (replaceLastMessage) {\n                this.state.replaceMessage(\n                  this.state.messages.length - 1,\n                  activeResponse.state.message\n                );\n              } else {\n                this.state.pushMessage(activeResponse.state.message);\n              }\n            }\n          })\n        )\n      );\n      await consumeStream({\n        stream: processUIMessageStream({\n          stream,\n          onToolCall: this.onToolCall,\n          onData: this.onData,\n          messageMetadataSchema: this.messageMetadataSchema,\n          dataPartSchemas: this.dataPartSchemas,\n          runUpdateMessageJob,\n          onError: (error) => {\n            throw error;\n          }\n        }),\n        onError: (error) => {\n          throw error;\n        }\n      });\n      this.setStatus({ status: \"ready\" });\n    } catch (err) {\n      if (isAbort || err.name === \"AbortError\") {\n        isAbort = true;\n        this.setStatus({ status: \"ready\" });\n        return null;\n      }\n      isError = true;\n      if (err instanceof TypeError && (err.message.toLowerCase().includes(\"fetch\") || err.message.toLowerCase().includes(\"network\"))) {\n        isDisconnect = true;\n      }\n      if (this.onError && err instanceof Error) {\n        this.onError(err);\n      }\n      this.setStatus({ status: \"error\", error: err });\n    } finally {\n      try {\n        (_b = this.onFinish) == null ? void 0 : _b.call(this, {\n          message: this.activeResponse.state.message,\n          messages: this.state.messages,\n          isAbort,\n          isDisconnect,\n          isError,\n          finishReason: (_a22 = this.activeResponse) == null ? void 0 : _a22.state.finishReason\n        });\n      } catch (err) {\n        console.error(err);\n      }\n      this.activeResponse = void 0;\n    }\n    if (!isError && await this.shouldSendAutomatically()) {\n      await this.makeRequest({\n        trigger: \"submit-message\",\n        messageId: (_c = this.lastMessage) == null ? void 0 : _c.id,\n        metadata,\n        headers,\n        body\n      });\n    }\n  }\n};\n\n// src/ui/direct-chat-transport.ts\nvar DirectChatTransport = class {\n  constructor({\n    agent,\n    options,\n    ...uiMessageStreamOptions\n  }) {\n    this.agent = agent;\n    this.agentOptions = options;\n    this.uiMessageStreamOptions = uiMessageStreamOptions;\n  }\n  async sendMessages({\n    messages,\n    abortSignal\n  }) {\n    const validatedMessages = await validateUIMessages({\n      messages,\n      // tools are compatible; the casting is required because the context param is\n      // not available in ui messages\n      tools: this.agent.tools\n    });\n    const modelMessages = await convertToModelMessages(validatedMessages, {\n      tools: this.agent.tools\n    });\n    const result = await this.agent.stream({\n      prompt: modelMessages,\n      abortSignal,\n      ...this.agentOptions !== void 0 ? { options: this.agentOptions } : {}\n    });\n    return toUIMessageStream({\n      ...this.uiMessageStreamOptions,\n      stream: result.stream,\n      tools: this.agent.tools\n    });\n  }\n  /**\n   * Direct transport does not support reconnection since there is no\n   * persistent server-side stream to reconnect to.\n   *\n   * @returns Always returns `null`\n   */\n  async reconnectToStream(_options) {\n    return null;\n  }\n};\n\n// src/ui/last-assistant-message-is-complete-with-approval-responses.ts\nfunction lastAssistantMessageIsCompleteWithApprovalResponses({\n  messages\n}) {\n  const message = messages[messages.length - 1];\n  if (!message) {\n    return false;\n  }\n  if (message.role !== \"assistant\") {\n    return false;\n  }\n  const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n    return part.type === \"step-start\" ? index : lastIndex;\n  }, -1);\n  const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolUIPart);\n  return (\n    // has at least one tool approval response\n    lastStepToolInvocations.filter((part) => part.state === \"approval-responded\").length > 0 && // all tool approvals must have a response\n    lastStepToolInvocations.every(\n      (part) => part.state === \"output-available\" || part.state === \"output-error\" || part.state === \"approval-responded\"\n    )\n  );\n}\n\n// src/ui/last-assistant-message-is-complete-with-tool-calls.ts\nfunction lastAssistantMessageIsCompleteWithToolCalls({\n  messages\n}) {\n  const message = messages[messages.length - 1];\n  if (!message) {\n    return false;\n  }\n  if (message.role !== \"assistant\") {\n    return false;\n  }\n  const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n    return part.type === \"step-start\" ? index : lastIndex;\n  }, -1);\n  const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolUIPart).filter((part) => !part.providerExecuted);\n  return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every(\n    (part) => part.state === \"output-available\" || part.state === \"output-error\"\n  );\n}\n\n// src/ui/transform-text-to-ui-message-stream.ts\nfunction transformTextToUiMessageStream({\n  stream\n}) {\n  return stream.pipeThrough(\n    new TransformStream({\n      start(controller) {\n        controller.enqueue({ type: \"start\" });\n        controller.enqueue({ type: \"start-step\" });\n        controller.enqueue({ type: \"text-start\", id: \"text-1\" });\n      },\n      async transform(part, controller) {\n        controller.enqueue({ type: \"text-delta\", id: \"text-1\", delta: part });\n      },\n      async flush(controller) {\n        controller.enqueue({ type: \"text-end\", id: \"text-1\" });\n        controller.enqueue({ type: \"finish-step\" });\n        controller.enqueue({ type: \"finish\" });\n      }\n    })\n  );\n}\n\n// src/ui/text-stream-chat-transport.ts\nvar TextStreamChatTransport = class extends HttpChatTransport {\n  constructor(options = {}) {\n    super(options);\n  }\n  processResponseStream(stream) {\n    return transformTextToUiMessageStream({\n      stream: stream.pipeThrough(new TextDecoderStream())\n    });\n  }\n};\n\n// src/upload-file/upload-file.ts\nimport {\n  convertBase64ToUint8Array as convertBase64ToUint8Array6,\n  detectMediaType as detectMediaType6\n} from \"@ai-sdk/provider-utils\";\nasync function uploadFile({\n  api,\n  data: dataArg,\n  mediaType: mediaTypeArg,\n  filename,\n  providerOptions\n}) {\n  var _a22;\n  const data = dataArg instanceof Uint8Array || typeof dataArg === \"string\" ? { type: \"data\", data: dataArg } : dataArg;\n  const mediaType = mediaTypeArg != null ? mediaTypeArg : data.type === \"text\" ? \"text/plain\" : (_a22 = detectMediaType6({ data: data.data })) != null ? _a22 : isLikelyText(data.data) ? \"text/plain\" : \"application/octet-stream\";\n  const filesApi = \"uploadFile\" in api ? api : typeof api.files === \"function\" ? api.files() : (() => {\n    throw new Error(\n      \"The provider does not support file uploads. Make sure it exposes a files() method.\"\n    );\n  })();\n  const result = await filesApi.uploadFile({\n    data,\n    mediaType,\n    filename,\n    providerOptions\n  });\n  return new DefaultUploadFileResult({\n    providerReference: result.providerReference,\n    mediaType: result.mediaType,\n    filename: result.filename,\n    providerMetadata: result.providerMetadata,\n    warnings: result.warnings\n  });\n}\nvar DefaultUploadFileResult = class {\n  constructor(options) {\n    this.providerReference = options.providerReference;\n    this.mediaType = options.mediaType;\n    this.filename = options.filename;\n    this.providerMetadata = options.providerMetadata;\n    this.warnings = options.warnings;\n  }\n};\nfunction isLikelyText(data) {\n  const CHECK_LENGTH = 512;\n  const BASE64_CHECK_LENGTH = Math.ceil((CHECK_LENGTH + 4) / 3) * 4;\n  const bytes = typeof data === \"string\" ? convertBase64ToUint8Array6(\n    data.substring(0, Math.min(data.length, BASE64_CHECK_LENGTH))\n  ) : data;\n  const checkLength = Math.min(bytes.length, CHECK_LENGTH);\n  if (checkLength === 0)\n    return false;\n  for (let i = 0; i < checkLength; i++) {\n    const byte = bytes[i];\n    if (byte === 0 || byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {\n      return false;\n    }\n  }\n  return true;\n}\n\n// src/upload-skill/upload-skill.ts\nasync function uploadSkill({\n  api,\n  files,\n  displayTitle,\n  providerOptions\n}) {\n  const skillsApi = \"uploadSkill\" in api ? api : typeof api.skills === \"function\" ? api.skills() : (() => {\n    throw new Error(\n      \"The provider does not support skills. Make sure it exposes a skills() method.\"\n    );\n  })();\n  const normalizedFiles = files.map((file) => ({\n    ...file,\n    data: file.data instanceof Uint8Array || typeof file.data === \"string\" ? { type: \"data\", data: file.data } : file.data\n  }));\n  const result = await skillsApi.uploadSkill({\n    files: normalizedFiles,\n    displayTitle,\n    providerOptions\n  });\n  return result;\n}\nexport {\n  AISDKError22 as AISDKError,\n  AI_SDK_TELEMETRY_TRACING_CHANNEL,\n  APICallError,\n  AbstractChat,\n  DefaultChatTransport,\n  DefaultGeneratedFile,\n  DirectChatTransport,\n  DownloadError,\n  EmptyResponseBodyError,\n  AbstractRealtimeSession as Experimental_AbstractRealtimeSession,\n  ToolLoopAgent as Experimental_Agent,\n  HttpChatTransport,\n  InvalidArgumentError,\n  InvalidDataContentError,\n  InvalidMessageRoleError,\n  InvalidPromptError,\n  InvalidResponseDataError,\n  InvalidStreamPartError,\n  InvalidToolApprovalError,\n  InvalidToolApprovalSignatureError,\n  InvalidToolInputError,\n  JSONParseError,\n  JsonToSseTransformStream,\n  LoadAPIKeyError,\n  LoadSettingError,\n  MessageConversionError,\n  MissingToolResultsError,\n  NoContentGeneratedError,\n  NoImageGeneratedError,\n  NoObjectGeneratedError,\n  NoOutputGeneratedError,\n  NoSpeechGeneratedError,\n  NoSuchModelError,\n  NoSuchProviderError,\n  NoSuchProviderReferenceError,\n  NoSuchToolError,\n  NoTranscriptGeneratedError,\n  NoVideoGeneratedError,\n  output_exports as Output,\n  RetryError,\n  SerialJobExecutor,\n  TextStreamChatTransport,\n  TooManyEmbeddingValuesForCallError,\n  ToolCallNotFoundForApprovalError,\n  ToolCallRepairError,\n  ToolLoopAgent,\n  TypeValidationError,\n  UIMessageStreamError,\n  UI_MESSAGE_STREAM_HEADERS,\n  UnsupportedFunctionalityError,\n  UnsupportedModelVersionError,\n  addToolInputExamplesMiddleware,\n  asSchema7 as asSchema,\n  assistantModelMessageSchema,\n  callCompletionApi,\n  consumeStream,\n  convertDataContentToBase64String,\n  convertFileListToFileUIParts,\n  convertToModelMessages,\n  cosineSimilarity,\n  createAgentUIStream,\n  createAgentUIStreamResponse,\n  createDownload,\n  createGateway,\n  createIdGenerator9 as createIdGenerator,\n  createProviderRegistry,\n  createTextStreamResponse,\n  createUIMessageStream,\n  createUIMessageStreamResponse,\n  customProvider,\n  defaultEmbeddingSettingsMiddleware,\n  defaultSettingsMiddleware,\n  dynamicTool,\n  embed,\n  embedMany,\n  experimental_createProviderRegistry,\n  decodeRealtimeAudio as experimental_decodeRealtimeAudio,\n  encodeRealtimeAudio as experimental_encodeRealtimeAudio,\n  filterActiveTools as experimental_filterActiveTools,\n  experimental_generateSpeech,\n  experimental_generateVideo,\n  getRealtimeToolDefinitions as experimental_getRealtimeToolDefinitions,\n  resampleAudio as experimental_resampleAudio,\n  streamLanguageModelCall as experimental_streamLanguageModelCall,\n  experimental_transcribe,\n  extractJsonMiddleware,\n  extractReasoningMiddleware,\n  gateway2 as gateway,\n  generateId,\n  generateImage,\n  generateObject,\n  generateSpeech,\n  generateText,\n  getChunkTimeoutMs,\n  getStaticToolName,\n  getStepTimeoutMs,\n  getTextFromDataUrl,\n  getToolName,\n  getToolOrDynamicToolName,\n  getToolTimeoutMs,\n  getTotalTimeoutMs,\n  hasToolCall,\n  isCustomContentUIPart,\n  isDataUIPart,\n  isDeepEqualData,\n  isDynamicToolUIPart,\n  isFileUIPart,\n  isLoopFinished,\n  isReasoningFileUIPart,\n  isReasoningUIPart,\n  isStaticToolUIPart,\n  isStepCount,\n  isTextUIPart,\n  isToolUIPart,\n  jsonSchema,\n  lastAssistantMessageIsCompleteWithApprovalResponses,\n  lastAssistantMessageIsCompleteWithToolCalls,\n  modelMessageSchema,\n  parseJsonEventStream3 as parseJsonEventStream,\n  parsePartialJson,\n  pipeAgentUIStreamToResponse,\n  pipeTextStreamToResponse,\n  pipeUIMessageStreamToResponse,\n  pruneMessages,\n  readUIMessageStream,\n  registerTelemetry,\n  rerank,\n  safeValidateUIMessages,\n  simulateReadableStream,\n  simulateStreamingMiddleware,\n  smoothStream,\n  isStepCount as stepCountIs,\n  streamObject,\n  streamText,\n  systemModelMessageSchema,\n  toTextStream,\n  toUIMessageChunk,\n  toUIMessageStream,\n  tool,\n  toolModelMessageSchema,\n  transcribe,\n  uiMessageChunkSchema,\n  uploadFile,\n  uploadSkill,\n  userModelMessageSchema,\n  validateUIMessages,\n  wrapEmbeddingModel,\n  wrapImageModel,\n  wrapLanguageModel,\n  wrapProvider,\n  zodSchema3 as zodSchema\n};\n//# sourceMappingURL=index.js.map","let crypto;\ncrypto =\n    globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL\n        globalThis.crypto ?? // Node.js >18\n        import(\"node:crypto\").then(m => m.webcrypto); // Node.js <18 Non-REPL\n/**\n * Creates an array of length `size` of random bytes\n * @param size\n * @returns Array of random ints (0 to 255)\n */\nasync function getRandomValues(size) {\n    return (await crypto).getRandomValues(new Uint8Array(size));\n}\n/** Generate cryptographically strong random string\n * @param size The desired length of the string\n * @returns The random string\n */\nasync function random(size) {\n    const mask = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\";\n    const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;\n    let result = \"\";\n    while (result.length < size) {\n        const randomBytes = await getRandomValues(size - result.length);\n        for (const randomByte of randomBytes) {\n            if (randomByte < evenDistCutoff) {\n                result += mask[randomByte % mask.length];\n            }\n        }\n    }\n    return result;\n}\n/** Generate a PKCE challenge verifier\n * @param length Length of the verifier\n * @returns A random verifier `length` characters long\n */\nasync function generateVerifier(length) {\n    return await random(length);\n}\n/** Generate a PKCE code challenge from a code verifier\n * @param code_verifier\n * @returns The base64 url encoded code challenge\n */\nexport async function generateChallenge(code_verifier) {\n    const buffer = await (await crypto).subtle.digest(\"SHA-256\", new TextEncoder().encode(code_verifier));\n    // Generate base64url string\n    // btoa is deprecated in Node.js but is used here for web browser compatibility\n    // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811)\n    return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n        .replace(/\\//g, '_')\n        .replace(/\\+/g, '-')\n        .replace(/=/g, '');\n}\n/** Generate a PKCE challenge pair\n * @param length Length of the verifer (between 43-128). Defaults to 43.\n * @returns PKCE challenge pair\n */\nexport default async function pkceChallenge(length) {\n    if (!length)\n        length = 43;\n    if (length < 43 || length > 128) {\n        throw `Expected a length between 43 and 128. Received ${length}.`;\n    }\n    const verifier = await generateVerifier(length);\n    const challenge = await generateChallenge(verifier);\n    return {\n        code_verifier: verifier,\n        code_challenge: challenge,\n    };\n}\n/** Verify that a code_verifier produces the expected code challenge\n * @param code_verifier\n * @param expectedChallenge The code challenge to verify\n * @returns True if challenges are equal. False otherwise.\n */\nexport async function verifyChallenge(code_verifier, expectedChallenge) {\n    const actualChallenge = await generateChallenge(code_verifier);\n    return actualChallenge === expectedChallenge;\n}\n","// src/tool/mcp-client.ts\nimport {\n  asSchema,\n  dynamicTool,\n  jsonSchema,\n  safeParseJSON,\n  safeValidateTypes,\n  tool\n} from \"@ai-sdk/provider-utils\";\n\n// src/error/mcp-client-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_MCPClientError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar MCPClientError = class extends (_b = AISDKError, _a = symbol, _b) {\n  constructor({\n    name: name3 = \"MCPClientError\",\n    message,\n    cause,\n    data,\n    code,\n    statusCode,\n    url,\n    responseBody\n  }) {\n    super({ name: name3, message, cause });\n    this[_a] = true;\n    this.data = data;\n    this.code = code;\n    this.statusCode = statusCode;\n    this.url = url;\n    this.responseBody = responseBody;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker);\n  }\n};\n\n// src/tool/mcp-sse-transport.ts\nimport {\n  EventSourceParserStream,\n  withUserAgentSuffix,\n  getRuntimeEnvironmentUserAgent\n} from \"@ai-sdk/provider-utils\";\n\n// src/tool/json-rpc-message.ts\nimport { parseJSON } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\n\n// src/tool/types.ts\nimport { z } from \"zod/v4\";\nvar LATEST_PROTOCOL_VERSION = \"2025-11-25\";\nvar SUPPORTED_PROTOCOL_VERSIONS = [\n  LATEST_PROTOCOL_VERSION,\n  \"2025-06-18\",\n  \"2025-03-26\",\n  \"2024-11-05\"\n];\nvar ToolMetaSchema = z.optional(z.record(z.string(), z.unknown()));\nvar ClientOrServerImplementationSchema = z.looseObject({\n  name: z.string(),\n  version: z.string(),\n  title: z.optional(z.string())\n});\nvar BaseParamsSchema = z.looseObject({\n  _meta: z.optional(z.object({}).loose())\n});\nvar ResultSchema = BaseParamsSchema;\nvar RequestSchema = z.object({\n  method: z.string(),\n  params: z.optional(BaseParamsSchema)\n});\nvar ElicitationCapabilitySchema = z.object({\n  applyDefaults: z.optional(z.boolean())\n}).loose();\nvar ServerCapabilitiesSchema = z.looseObject({\n  experimental: z.optional(z.object({}).loose()),\n  logging: z.optional(z.object({}).loose()),\n  completions: z.optional(z.object({}).loose()),\n  prompts: z.optional(\n    z.looseObject({\n      listChanged: z.optional(z.boolean())\n    })\n  ),\n  resources: z.optional(\n    z.looseObject({\n      subscribe: z.optional(z.boolean()),\n      listChanged: z.optional(z.boolean())\n    })\n  ),\n  tools: z.optional(\n    z.looseObject({\n      listChanged: z.optional(z.boolean())\n    })\n  ),\n  elicitation: z.optional(ElicitationCapabilitySchema)\n});\nvar ClientCapabilitiesSchema = z.object({\n  elicitation: z.optional(ElicitationCapabilitySchema)\n}).loose();\nvar InitializeResultSchema = ResultSchema.extend({\n  protocolVersion: z.string(),\n  capabilities: ServerCapabilitiesSchema,\n  serverInfo: ClientOrServerImplementationSchema,\n  instructions: z.optional(z.string())\n});\nvar PaginatedResultSchema = ResultSchema.extend({\n  nextCursor: z.optional(z.string())\n});\nvar ToolSchema = z.object({\n  name: z.string(),\n  /**\n   * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool\n   */\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  inputSchema: z.object({\n    type: z.literal(\"object\"),\n    properties: z.optional(z.object({}).loose())\n  }).loose(),\n  /**\n   * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema\n   */\n  outputSchema: z.optional(z.object({}).loose()),\n  annotations: z.optional(\n    z.object({\n      title: z.optional(z.string())\n    }).loose()\n  ),\n  _meta: ToolMetaSchema\n}).loose();\nvar ListToolsResultSchema = PaginatedResultSchema.extend({\n  tools: z.array(ToolSchema)\n});\nvar TextContentSchema = z.object({\n  type: z.literal(\"text\"),\n  text: z.string()\n}).loose();\nvar ImageContentSchema = z.object({\n  type: z.literal(\"image\"),\n  data: z.base64(),\n  mimeType: z.string()\n}).loose();\nvar ResourceSchema = z.object({\n  uri: z.string(),\n  name: z.string(),\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  mimeType: z.optional(z.string()),\n  size: z.optional(z.number())\n}).loose();\nvar ListResourcesResultSchema = PaginatedResultSchema.extend({\n  resources: z.array(ResourceSchema)\n});\nvar ResourceContentsSchema = z.object({\n  /**\n   * The URI of this resource.\n   */\n  uri: z.string(),\n  /**\n   * Optional display name of the resource content.\n   */\n  name: z.optional(z.string()),\n  /**\n   * Optional human readable title.\n   */\n  title: z.optional(z.string()),\n  /**\n   * The MIME type of this resource, if known.\n   */\n  mimeType: z.optional(z.string())\n}).loose();\nvar TextResourceContentsSchema = ResourceContentsSchema.extend({\n  text: z.string()\n});\nvar BlobResourceContentsSchema = ResourceContentsSchema.extend({\n  blob: z.base64()\n});\nvar EmbeddedResourceSchema = z.object({\n  type: z.literal(\"resource\"),\n  resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])\n}).loose();\nvar ResourceLinkContentSchema = z.object({\n  type: z.literal(\"resource_link\"),\n  uri: z.string(),\n  name: z.string(),\n  description: z.optional(z.string()),\n  mimeType: z.optional(z.string())\n}).loose();\nvar CallToolResultSchema = ResultSchema.extend({\n  content: z.array(\n    z.union([\n      TextContentSchema,\n      ImageContentSchema,\n      EmbeddedResourceSchema,\n      ResourceLinkContentSchema\n    ])\n  ),\n  /**\n   * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content\n   */\n  structuredContent: z.optional(z.unknown()),\n  isError: z.boolean().default(false).optional()\n}).or(\n  ResultSchema.extend({\n    toolResult: z.unknown()\n  })\n);\nvar ResourceTemplateSchema = z.object({\n  uriTemplate: z.string(),\n  name: z.string(),\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  mimeType: z.optional(z.string())\n}).loose();\nvar ListResourceTemplatesResultSchema = ResultSchema.extend({\n  resourceTemplates: z.array(ResourceTemplateSchema)\n});\nvar ReadResourceResultSchema = ResultSchema.extend({\n  contents: z.array(\n    z.union([TextResourceContentsSchema, BlobResourceContentsSchema])\n  )\n});\nvar PromptReferenceSchema = z.object({\n  type: z.literal(\"ref/prompt\"),\n  name: z.string()\n}).loose();\nvar ResourceReferenceSchema = z.object({\n  type: z.literal(\"ref/resource\"),\n  uri: z.string()\n}).loose();\nvar CompletionArgumentSchema = z.object({\n  name: z.string(),\n  value: z.string()\n}).loose();\nvar CompleteRequestParamsSchema = BaseParamsSchema.extend({\n  ref: z.union([PromptReferenceSchema, ResourceReferenceSchema]),\n  argument: CompletionArgumentSchema,\n  context: z.optional(\n    z.object({\n      arguments: z.record(z.string(), z.string())\n    }).loose()\n  )\n});\nvar CompleteResultSchema = ResultSchema.extend({\n  completion: z.object({\n    values: z.array(z.string()).max(100),\n    total: z.optional(z.number().int()),\n    hasMore: z.optional(z.boolean())\n  }).loose()\n});\nvar PromptArgumentSchema = z.object({\n  name: z.string(),\n  description: z.optional(z.string()),\n  required: z.optional(z.boolean())\n}).loose();\nvar PromptSchema = z.object({\n  name: z.string(),\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  arguments: z.optional(z.array(PromptArgumentSchema))\n}).loose();\nvar ListPromptsResultSchema = PaginatedResultSchema.extend({\n  prompts: z.array(PromptSchema)\n});\nvar PromptMessageSchema = z.object({\n  role: z.union([z.literal(\"user\"), z.literal(\"assistant\")]),\n  content: z.union([\n    TextContentSchema,\n    ImageContentSchema,\n    EmbeddedResourceSchema,\n    ResourceLinkContentSchema\n  ])\n}).loose();\nvar GetPromptResultSchema = ResultSchema.extend({\n  description: z.optional(z.string()),\n  messages: z.array(PromptMessageSchema)\n});\nvar ElicitationRequestParamsSchema = BaseParamsSchema.extend({\n  message: z.string(),\n  requestedSchema: z.unknown()\n});\nvar ElicitationRequestSchema = RequestSchema.extend({\n  method: z.literal(\"elicitation/create\"),\n  params: ElicitationRequestParamsSchema\n});\nvar ElicitResultSchema = ResultSchema.extend({\n  action: z.union([\n    z.literal(\"accept\"),\n    z.literal(\"decline\"),\n    z.literal(\"cancel\")\n  ]),\n  content: z.optional(z.record(z.string(), z.unknown()))\n});\n\n// src/tool/json-rpc-message.ts\nvar JSONRPC_VERSION = \"2.0\";\nvar JSONRPCRequestSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION),\n  id: z2.union([z2.string(), z2.number().int()])\n}).merge(RequestSchema).strict();\nvar JSONRPCResponseSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION),\n  id: z2.union([z2.string(), z2.number().int()]),\n  result: ResultSchema\n}).strict();\nvar JSONRPCErrorSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION),\n  id: z2.union([z2.string(), z2.number().int()]),\n  error: z2.object({\n    code: z2.number().int(),\n    message: z2.string(),\n    data: z2.optional(z2.unknown())\n  })\n}).strict();\nvar JSONRPCNotificationSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION)\n}).merge(\n  z2.object({\n    method: z2.string(),\n    params: z2.optional(BaseParamsSchema)\n  })\n).strict();\nvar JSONRPCMessageSchema = z2.union([\n  JSONRPCRequestSchema,\n  JSONRPCNotificationSchema,\n  JSONRPCResponseSchema,\n  JSONRPCErrorSchema\n]);\nasync function parseJSONRPCMessage(text) {\n  return JSONRPCMessageSchema.parse(await parseJSON({ text }));\n}\n\n// src/version.ts\nvar VERSION = typeof __PACKAGE_VERSION__ !== \"undefined\" ? __PACKAGE_VERSION__ : \"0.0.0-test\";\n\n// src/tool/oauth.ts\nimport pkceChallenge from \"pkce-challenge\";\n\n// src/tool/oauth-types.ts\nimport { z as z3 } from \"zod/v4\";\nvar SafeUrlSchema = z3.string().url().superRefine((val, ctx) => {\n  if (!URL.canParse(val)) {\n    ctx.addIssue({\n      code: z3.ZodIssueCode.custom,\n      message: \"URL must be parseable\",\n      fatal: true\n    });\n    return z3.NEVER;\n  }\n}).refine(\n  (url) => {\n    const parsedUrl = new URL(url);\n    return parsedUrl.protocol !== \"javascript:\" && parsedUrl.protocol !== \"data:\" && parsedUrl.protocol !== \"vbscript:\";\n  },\n  { message: \"URL cannot use javascript:, data:, or vbscript: scheme\" }\n);\nvar OAuthTokensSchema = z3.object({\n  access_token: z3.string(),\n  id_token: z3.string().optional(),\n  // Optional for OAuth 2.1, but necessary in OpenID Connect\n  token_type: z3.string(),\n  expires_in: z3.number().optional(),\n  scope: z3.string().optional(),\n  refresh_token: z3.string().optional(),\n  authorization_server: SafeUrlSchema.optional(),\n  token_endpoint: SafeUrlSchema.optional()\n}).strip();\nvar OAuthProtectedResourceMetadataSchema = z3.looseObject({\n  resource: z3.string().url(),\n  authorization_servers: z3.array(SafeUrlSchema).optional(),\n  jwks_uri: z3.string().url().optional(),\n  scopes_supported: z3.array(z3.string()).optional(),\n  bearer_methods_supported: z3.array(z3.string()).optional(),\n  resource_signing_alg_values_supported: z3.array(z3.string()).optional(),\n  resource_name: z3.string().optional(),\n  resource_documentation: z3.string().optional(),\n  resource_policy_uri: z3.string().url().optional(),\n  resource_tos_uri: z3.string().url().optional(),\n  tls_client_certificate_bound_access_tokens: z3.boolean().optional(),\n  authorization_details_types_supported: z3.array(z3.string()).optional(),\n  dpop_signing_alg_values_supported: z3.array(z3.string()).optional(),\n  dpop_bound_access_tokens_required: z3.boolean().optional()\n});\nvar OAuthMetadataSchema = z3.looseObject({\n  issuer: z3.string(),\n  authorization_endpoint: SafeUrlSchema,\n  token_endpoint: SafeUrlSchema,\n  registration_endpoint: SafeUrlSchema.optional(),\n  scopes_supported: z3.array(z3.string()).optional(),\n  response_types_supported: z3.array(z3.string()),\n  grant_types_supported: z3.array(z3.string()).optional(),\n  code_challenge_methods_supported: z3.array(z3.string()),\n  token_endpoint_auth_methods_supported: z3.array(z3.string()).optional(),\n  token_endpoint_auth_signing_alg_values_supported: z3.array(z3.string()).optional()\n});\nvar OpenIdProviderMetadataSchema = z3.looseObject({\n  issuer: z3.string(),\n  authorization_endpoint: SafeUrlSchema,\n  token_endpoint: SafeUrlSchema,\n  userinfo_endpoint: SafeUrlSchema.optional(),\n  jwks_uri: SafeUrlSchema,\n  registration_endpoint: SafeUrlSchema.optional(),\n  scopes_supported: z3.array(z3.string()).optional(),\n  response_types_supported: z3.array(z3.string()),\n  grant_types_supported: z3.array(z3.string()).optional(),\n  subject_types_supported: z3.array(z3.string()),\n  id_token_signing_alg_values_supported: z3.array(z3.string()),\n  claims_supported: z3.array(z3.string()).optional(),\n  token_endpoint_auth_methods_supported: z3.array(z3.string()).optional()\n});\nvar OpenIdProviderDiscoveryMetadataSchema = OpenIdProviderMetadataSchema.merge(\n  OAuthMetadataSchema.pick({\n    code_challenge_methods_supported: true\n  })\n);\nvar OAuthClientInformationSchema = z3.object({\n  client_id: z3.string(),\n  client_secret: z3.string().optional(),\n  client_id_issued_at: z3.number().optional(),\n  client_secret_expires_at: z3.number().optional(),\n  authorization_server: SafeUrlSchema.optional(),\n  token_endpoint: SafeUrlSchema.optional()\n}).strip();\nvar OAuthClientMetadataSchema = z3.object({\n  redirect_uris: z3.array(SafeUrlSchema),\n  token_endpoint_auth_method: z3.string().optional(),\n  grant_types: z3.array(z3.string()).optional(),\n  response_types: z3.array(z3.string()).optional(),\n  client_name: z3.string().optional(),\n  client_uri: SafeUrlSchema.optional(),\n  logo_uri: SafeUrlSchema.optional(),\n  scope: z3.string().optional(),\n  contacts: z3.array(z3.string()).optional(),\n  tos_uri: SafeUrlSchema.optional(),\n  policy_uri: z3.string().optional(),\n  jwks_uri: SafeUrlSchema.optional(),\n  jwks: z3.any().optional(),\n  software_id: z3.string().optional(),\n  software_version: z3.string().optional(),\n  software_statement: z3.string().optional()\n}).strip();\nvar OAuthErrorResponseSchema = z3.object({\n  error: z3.string(),\n  error_description: z3.string().optional(),\n  error_uri: z3.string().optional()\n});\nvar OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(\n  OAuthClientInformationSchema\n);\n\n// src/error/oauth-error.ts\nimport { AISDKError as AISDKError2 } from \"@ai-sdk/provider\";\nvar name2 = \"AI_MCPClientOAuthError\";\nvar marker2 = `vercel.ai.error.${name2}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar MCPClientOAuthError = class extends (_b2 = AISDKError2, _a2 = symbol2, _b2) {\n  constructor({\n    name: name3 = \"MCPClientOAuthError\",\n    message,\n    cause\n  }) {\n    super({ name: name3, message, cause });\n    this[_a2] = true;\n  }\n  static isInstance(error) {\n    return AISDKError2.hasMarker(error, marker2);\n  }\n};\nvar ServerError = class extends MCPClientOAuthError {\n};\nServerError.errorCode = \"server_error\";\nvar InvalidClientError = class extends MCPClientOAuthError {\n};\nInvalidClientError.errorCode = \"invalid_client\";\nvar InvalidGrantError = class extends MCPClientOAuthError {\n};\nInvalidGrantError.errorCode = \"invalid_grant\";\nvar UnauthorizedClientError = class extends MCPClientOAuthError {\n};\nUnauthorizedClientError.errorCode = \"unauthorized_client\";\nvar OAUTH_ERRORS = {\n  [ServerError.errorCode]: ServerError,\n  [InvalidClientError.errorCode]: InvalidClientError,\n  [InvalidGrantError.errorCode]: InvalidGrantError,\n  [UnauthorizedClientError.errorCode]: UnauthorizedClientError\n};\n\n// src/util/oauth-util.ts\nfunction resourceUrlFromServerUrl(url) {\n  const resourceURL = typeof url === \"string\" ? new URL(url) : new URL(url.href);\n  resourceURL.hash = \"\";\n  return resourceURL;\n}\nfunction resourceUrlStripSlash(resource) {\n  const href = resource.href;\n  if (resource.pathname === \"/\" && href.endsWith(\"/\")) {\n    return href.slice(0, -1);\n  }\n  return href;\n}\nfunction checkResourceAllowed({\n  requestedResource,\n  configuredResource\n}) {\n  const requested = typeof requestedResource === \"string\" ? new URL(requestedResource) : new URL(requestedResource.href);\n  const configured = typeof configuredResource === \"string\" ? new URL(configuredResource) : new URL(configuredResource.href);\n  if (requested.origin !== configured.origin) {\n    return false;\n  }\n  if (requested.pathname.length < configured.pathname.length) {\n    return false;\n  }\n  const requestedPath = requested.pathname.endsWith(\"/\") ? requested.pathname : requested.pathname + \"/\";\n  const configuredPath = configured.pathname.endsWith(\"/\") ? configured.pathname : configured.pathname + \"/\";\n  return requestedPath.startsWith(configuredPath);\n}\n\n// src/tool/oauth.ts\nimport { parseJSON as parseJSON2 } from \"@ai-sdk/provider-utils\";\nvar UnauthorizedError = class extends Error {\n  constructor(message = \"Unauthorized\") {\n    super(message);\n    this.name = \"UnauthorizedError\";\n  }\n};\nfunction normalizeUrl(url) {\n  return new URL(url).href;\n}\nfunction createAuthorizationServerInformation(authorizationServerUrl, metadata) {\n  return {\n    authorizationServerUrl: normalizeUrl(authorizationServerUrl),\n    tokenEndpoint: normalizeUrl(\n      (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL(\"/token\", authorizationServerUrl)\n    )\n  };\n}\nfunction addAuthorizationServerInformationToTokens(tokens, authorizationServerInformation) {\n  return {\n    ...tokens,\n    authorization_server: authorizationServerInformation.authorizationServerUrl,\n    token_endpoint: authorizationServerInformation.tokenEndpoint\n  };\n}\nfunction addAuthorizationServerInformationToClientInformation(clientInformation, authorizationServerInformation) {\n  return {\n    ...clientInformation,\n    authorization_server: authorizationServerInformation.authorizationServerUrl,\n    token_endpoint: authorizationServerInformation.tokenEndpoint\n  };\n}\nfunction getAuthorizationServerInformationFromCredentials(credentials) {\n  if (!(credentials == null ? void 0 : credentials.authorization_server) || !credentials.token_endpoint) {\n    return void 0;\n  }\n  return {\n    authorizationServerUrl: normalizeUrl(credentials.authorization_server),\n    tokenEndpoint: normalizeUrl(credentials.token_endpoint)\n  };\n}\nasync function getStoredAuthorizationServerInformation({\n  provider,\n  clientInformation,\n  tokens\n}) {\n  var _a3;\n  const tokenAuthorizationServerInformation = getAuthorizationServerInformationFromCredentials(tokens);\n  if (tokenAuthorizationServerInformation) {\n    return tokenAuthorizationServerInformation;\n  }\n  const providerAuthorizationServerInformation = await ((_a3 = provider.authorizationServerInformation) == null ? void 0 : _a3.call(provider));\n  if (providerAuthorizationServerInformation) {\n    return {\n      authorizationServerUrl: normalizeUrl(\n        providerAuthorizationServerInformation.authorizationServerUrl\n      ),\n      tokenEndpoint: normalizeUrl(\n        providerAuthorizationServerInformation.tokenEndpoint\n      )\n    };\n  }\n  return getAuthorizationServerInformationFromCredentials(clientInformation);\n}\nasync function saveAuthorizationServerInformation({\n  provider,\n  clientInformation,\n  authorizationServerInformation\n}) {\n  if (provider.saveAuthorizationServerInformation) {\n    await provider.saveAuthorizationServerInformation(\n      authorizationServerInformation\n    );\n    return true;\n  }\n  if (provider.saveClientInformation) {\n    await provider.saveClientInformation(\n      addAuthorizationServerInformationToClientInformation(\n        clientInformation,\n        authorizationServerInformation\n      )\n    );\n    return true;\n  }\n  return false;\n}\nfunction assertResourceMetadataUrlSameOrigin(serverUrl, resourceMetadataUrl) {\n  if (!resourceMetadataUrl) {\n    return;\n  }\n  const expectedOrigin = new URL(serverUrl).origin;\n  if (resourceMetadataUrl.origin !== expectedOrigin) {\n    throw new MCPClientOAuthError({\n      message: `OAuth protected resource metadata URL ${resourceMetadataUrl.href} must have the same origin as the MCP server URL ${expectedOrigin}`\n    });\n  }\n}\nfunction assertAuthorizationServerInformationMatches({\n  storedAuthorizationServerInformation,\n  currentAuthorizationServerInformation\n}) {\n  if (storedAuthorizationServerInformation.authorizationServerUrl !== currentAuthorizationServerInformation.authorizationServerUrl || storedAuthorizationServerInformation.tokenEndpoint !== currentAuthorizationServerInformation.tokenEndpoint) {\n    throw new MCPClientOAuthError({\n      message: \"OAuth authorization server metadata does not match the metadata that issued the stored credentials\"\n    });\n  }\n}\nfunction extractResourceMetadataUrl(response) {\n  var _a3;\n  const header = (_a3 = response.headers.get(\"www-authenticate\")) != null ? _a3 : response.headers.get(\"WWW-Authenticate\");\n  if (!header) {\n    return void 0;\n  }\n  const [type, scheme] = header.split(\" \");\n  if (type.toLowerCase() !== \"bearer\" || !scheme) {\n    return void 0;\n  }\n  const regex = /resource_metadata=\"([^\"]*)\"/;\n  const match = header.match(regex);\n  if (!match) {\n    return void 0;\n  }\n  try {\n    return new URL(match[1]);\n  } catch (e) {\n    return void 0;\n  }\n}\nfunction buildWellKnownPath(wellKnownPrefix, pathname = \"\", options = {}) {\n  if (pathname.endsWith(\"/\")) {\n    pathname = pathname.slice(0, -1);\n  }\n  return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;\n}\nasync function fetchWithCorsRetry(url, headers, fetchFn = fetch) {\n  try {\n    return await fetchFn(url, { headers });\n  } catch (error) {\n    if (error instanceof TypeError) {\n      if (headers) {\n        return fetchWithCorsRetry(url, void 0, fetchFn);\n      } else {\n        return void 0;\n      }\n    }\n    throw error;\n  }\n}\nasync function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {\n  const headers = {\n    \"MCP-Protocol-Version\": protocolVersion\n  };\n  return await fetchWithCorsRetry(url, headers, fetchFn);\n}\nfunction shouldAttemptFallback(response, pathname) {\n  return !response || response.status >= 400 && response.status < 500 && pathname !== \"/\";\n}\nasync function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {\n  var _a3, _b3;\n  const issuer = new URL(serverUrl);\n  const protocolVersion = (_a3 = opts == null ? void 0 : opts.protocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION;\n  let url;\n  if (opts == null ? void 0 : opts.metadataUrl) {\n    url = new URL(opts.metadataUrl);\n  } else {\n    const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);\n    url = new URL(wellKnownPath, (_b3 = opts == null ? void 0 : opts.metadataServerUrl) != null ? _b3 : issuer);\n    url.search = issuer.search;\n  }\n  let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);\n  if (!(opts == null ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {\n    const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);\n    response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);\n  }\n  return response;\n}\nasync function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {\n  const response = await discoverMetadataWithFallback(\n    serverUrl,\n    \"oauth-protected-resource\",\n    fetchFn,\n    {\n      protocolVersion: opts == null ? void 0 : opts.protocolVersion,\n      metadataUrl: opts == null ? void 0 : opts.resourceMetadataUrl\n    }\n  );\n  if (!response || response.status === 404) {\n    throw new Error(\n      `Resource server does not implement OAuth 2.0 Protected Resource Metadata.`\n    );\n  }\n  if (!response.ok) {\n    throw new Error(\n      `HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`\n    );\n  }\n  return OAuthProtectedResourceMetadataSchema.parse(await response.json());\n}\nfunction buildDiscoveryUrls(authorizationServerUrl) {\n  const url = typeof authorizationServerUrl === \"string\" ? new URL(authorizationServerUrl) : authorizationServerUrl;\n  const hasPath = url.pathname !== \"/\";\n  const rootIssuer = url.origin;\n  const urlsToTry = [];\n  if (!hasPath) {\n    urlsToTry.push({\n      url: new URL(\"/.well-known/oauth-authorization-server\", url.origin),\n      type: \"oauth\",\n      expectedIssuer: rootIssuer\n    });\n    urlsToTry.push({\n      url: new URL(\"/.well-known/openid-configuration\", url.origin),\n      type: \"oidc\",\n      expectedIssuer: rootIssuer\n    });\n    return urlsToTry;\n  }\n  let pathname = url.pathname;\n  if (pathname.endsWith(\"/\")) {\n    pathname = pathname.slice(0, -1);\n  }\n  const pathIssuer = `${url.origin}${pathname}`;\n  urlsToTry.push({\n    url: new URL(\n      `/.well-known/oauth-authorization-server${pathname}`,\n      url.origin\n    ),\n    type: \"oauth\",\n    expectedIssuer: pathIssuer\n  });\n  urlsToTry.push({\n    url: new URL(\"/.well-known/oauth-authorization-server\", url.origin),\n    type: \"oauth\",\n    expectedIssuer: rootIssuer\n  });\n  urlsToTry.push({\n    url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),\n    type: \"oidc\",\n    expectedIssuer: pathIssuer\n  });\n  urlsToTry.push({\n    url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),\n    type: \"oidc\",\n    expectedIssuer: pathIssuer\n  });\n  return urlsToTry;\n}\nfunction assertMetadataIssuerMatches(metadata, expectedIssuer) {\n  if (metadata.issuer !== expectedIssuer) {\n    throw new MCPClientOAuthError({\n      message: `OAuth authorization server metadata issuer ${metadata.issuer} does not match expected issuer ${expectedIssuer}`\n    });\n  }\n}\nasync function discoverAuthorizationServerMetadata(authorizationServerUrl, {\n  fetchFn = fetch,\n  protocolVersion = LATEST_PROTOCOL_VERSION\n} = {}) {\n  var _a3;\n  const headers = { \"MCP-Protocol-Version\": protocolVersion };\n  const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);\n  for (const { url: endpointUrl, type, expectedIssuer } of urlsToTry) {\n    const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);\n    if (!response) {\n      continue;\n    }\n    if (!response.ok) {\n      if (response.status >= 400 && response.status < 500) {\n        continue;\n      }\n      throw new Error(\n        `HTTP ${response.status} trying to load ${type === \"oauth\" ? \"OAuth\" : \"OpenID provider\"} metadata from ${endpointUrl}`\n      );\n    }\n    if (type === \"oauth\") {\n      const metadata = OAuthMetadataSchema.parse(await response.json());\n      assertMetadataIssuerMatches(metadata, expectedIssuer);\n      return metadata;\n    } else {\n      const metadata = OpenIdProviderDiscoveryMetadataSchema.parse(\n        await response.json()\n      );\n      assertMetadataIssuerMatches(metadata, expectedIssuer);\n      if (!((_a3 = metadata.code_challenge_methods_supported) == null ? void 0 : _a3.includes(\"S256\"))) {\n        throw new Error(\n          `Incompatible OIDC provider at ${endpointUrl}: does not support S256 code challenge method required by MCP specification`\n        );\n      }\n      return metadata;\n    }\n  }\n  return void 0;\n}\nasync function startAuthorization(authorizationServerUrl, {\n  metadata,\n  clientInformation,\n  redirectUrl,\n  scope,\n  state,\n  resource\n}) {\n  const responseType = \"code\";\n  const codeChallengeMethod = \"S256\";\n  let authorizationUrl;\n  if (metadata) {\n    authorizationUrl = new URL(metadata.authorization_endpoint);\n    if (!metadata.response_types_supported.includes(responseType)) {\n      throw new Error(\n        `Incompatible auth server: does not support response type ${responseType}`\n      );\n    }\n    if (!metadata.code_challenge_methods_supported || !metadata.code_challenge_methods_supported.includes(codeChallengeMethod)) {\n      throw new Error(\n        `Incompatible auth server: does not support code challenge method ${codeChallengeMethod}`\n      );\n    }\n  } else {\n    authorizationUrl = new URL(\"/authorize\", authorizationServerUrl);\n  }\n  const challenge = await pkceChallenge();\n  const codeVerifier = challenge.code_verifier;\n  const codeChallenge = challenge.code_challenge;\n  authorizationUrl.searchParams.set(\"response_type\", responseType);\n  authorizationUrl.searchParams.set(\"client_id\", clientInformation.client_id);\n  authorizationUrl.searchParams.set(\"code_challenge\", codeChallenge);\n  authorizationUrl.searchParams.set(\n    \"code_challenge_method\",\n    codeChallengeMethod\n  );\n  authorizationUrl.searchParams.set(\"redirect_uri\", String(redirectUrl));\n  if (state) {\n    authorizationUrl.searchParams.set(\"state\", state);\n  }\n  if (scope) {\n    authorizationUrl.searchParams.set(\"scope\", scope);\n  }\n  if (scope == null ? void 0 : scope.includes(\"offline_access\")) {\n    authorizationUrl.searchParams.append(\"prompt\", \"consent\");\n  }\n  if (resource) {\n    authorizationUrl.searchParams.set(\n      \"resource\",\n      resourceUrlStripSlash(resource)\n    );\n  }\n  return { authorizationUrl, codeVerifier };\n}\nfunction selectClientAuthMethod(clientInformation, supportedMethods) {\n  const hasClientSecret = clientInformation.client_secret !== void 0;\n  if (supportedMethods.length === 0) {\n    return hasClientSecret ? \"client_secret_post\" : \"none\";\n  }\n  if (hasClientSecret && supportedMethods.includes(\"client_secret_basic\")) {\n    return \"client_secret_basic\";\n  }\n  if (hasClientSecret && supportedMethods.includes(\"client_secret_post\")) {\n    return \"client_secret_post\";\n  }\n  if (supportedMethods.includes(\"none\")) {\n    return \"none\";\n  }\n  return hasClientSecret ? \"client_secret_post\" : \"none\";\n}\nfunction applyClientAuthentication(method, clientInformation, headers, params) {\n  const { client_id, client_secret } = clientInformation;\n  switch (method) {\n    case \"client_secret_basic\":\n      applyBasicAuth(client_id, client_secret, headers);\n      return;\n    case \"client_secret_post\":\n      applyPostAuth(client_id, client_secret, params);\n      return;\n    case \"none\":\n      applyPublicAuth(client_id, params);\n      return;\n    default:\n      throw new Error(`Unsupported client authentication method: ${method}`);\n  }\n}\nfunction applyBasicAuth(clientId, clientSecret, headers) {\n  if (!clientSecret) {\n    throw new Error(\n      \"client_secret_basic authentication requires a client_secret\"\n    );\n  }\n  const credentials = btoa(`${clientId}:${clientSecret}`);\n  headers.set(\"Authorization\", `Basic ${credentials}`);\n}\nfunction applyPostAuth(clientId, clientSecret, params) {\n  params.set(\"client_id\", clientId);\n  if (clientSecret) {\n    params.set(\"client_secret\", clientSecret);\n  }\n}\nfunction applyPublicAuth(clientId, params) {\n  params.set(\"client_id\", clientId);\n}\nasync function parseErrorResponse(input) {\n  const statusCode = input instanceof Response ? input.status : void 0;\n  const body = input instanceof Response ? await input.text() : input;\n  try {\n    const result = OAuthErrorResponseSchema.parse(\n      await parseJSON2({ text: body })\n    );\n    const { error, error_description, error_uri } = result;\n    const errorClass = OAUTH_ERRORS[error] || ServerError;\n    return new errorClass({\n      message: error_description || \"\",\n      cause: error_uri\n    });\n  } catch (error) {\n    const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : \"\"}Invalid OAuth error response: ${error}. Raw body: ${body}`;\n    return new ServerError({ message: errorMessage });\n  }\n}\nasync function exchangeAuthorization(authorizationServerUrl, {\n  metadata,\n  clientInformation,\n  authorizationCode,\n  codeVerifier,\n  redirectUri,\n  resource,\n  addClientAuthentication,\n  fetchFn\n}) {\n  var _a3;\n  const grantType = \"authorization_code\";\n  const tokenUrl = (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL(\"/token\", authorizationServerUrl);\n  if ((metadata == null ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) {\n    throw new Error(\n      `Incompatible auth server: does not support grant type ${grantType}`\n    );\n  }\n  const headers = new Headers({\n    \"Content-Type\": \"application/x-www-form-urlencoded\",\n    Accept: \"application/json\"\n  });\n  const params = new URLSearchParams({\n    grant_type: grantType,\n    code: authorizationCode,\n    code_verifier: codeVerifier,\n    redirect_uri: String(redirectUri)\n  });\n  if (addClientAuthentication) {\n    await addClientAuthentication(\n      headers,\n      params,\n      authorizationServerUrl,\n      metadata\n    );\n  } else {\n    const supportedMethods = (_a3 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a3 : [];\n    const authMethod = selectClientAuthMethod(\n      clientInformation,\n      supportedMethods\n    );\n    applyClientAuthentication(authMethod, clientInformation, headers, params);\n  }\n  if (resource) {\n    params.set(\"resource\", resourceUrlStripSlash(resource));\n  }\n  const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, {\n    method: \"POST\",\n    headers,\n    body: params\n  });\n  if (!response.ok) {\n    throw await parseErrorResponse(response);\n  }\n  return OAuthTokensSchema.parse(await response.json());\n}\nasync function refreshAuthorization(authorizationServerUrl, {\n  metadata,\n  clientInformation,\n  refreshToken,\n  resource,\n  addClientAuthentication,\n  fetchFn\n}) {\n  var _a3;\n  const grantType = \"refresh_token\";\n  let tokenUrl;\n  if (metadata) {\n    tokenUrl = new URL(metadata.token_endpoint);\n    if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) {\n      throw new Error(\n        `Incompatible auth server: does not support grant type ${grantType}`\n      );\n    }\n  } else {\n    tokenUrl = new URL(\"/token\", authorizationServerUrl);\n  }\n  const headers = new Headers({\n    \"Content-Type\": \"application/x-www-form-urlencoded\",\n    Accept: \"application/json\"\n  });\n  const params = new URLSearchParams({\n    grant_type: grantType,\n    refresh_token: refreshToken\n  });\n  if (addClientAuthentication) {\n    await addClientAuthentication(\n      headers,\n      params,\n      authorizationServerUrl,\n      metadata\n    );\n  } else {\n    const supportedMethods = (_a3 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a3 : [];\n    const authMethod = selectClientAuthMethod(\n      clientInformation,\n      supportedMethods\n    );\n    applyClientAuthentication(authMethod, clientInformation, headers, params);\n  }\n  if (resource) {\n    params.set(\"resource\", resourceUrlStripSlash(resource));\n  }\n  const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, {\n    method: \"POST\",\n    headers,\n    body: params\n  });\n  if (!response.ok) {\n    throw await parseErrorResponse(response);\n  }\n  return OAuthTokensSchema.parse({\n    refresh_token: refreshToken,\n    ...await response.json()\n  });\n}\nasync function registerClient(authorizationServerUrl, {\n  metadata,\n  clientMetadata,\n  fetchFn\n}) {\n  let registrationUrl;\n  if (metadata) {\n    if (!metadata.registration_endpoint) {\n      throw new Error(\n        \"Incompatible auth server: does not support dynamic client registration\"\n      );\n    }\n    registrationUrl = new URL(metadata.registration_endpoint);\n  } else {\n    registrationUrl = new URL(\"/register\", authorizationServerUrl);\n  }\n  const response = await (fetchFn != null ? fetchFn : fetch)(registrationUrl, {\n    method: \"POST\",\n    headers: {\n      \"Content-Type\": \"application/json\"\n    },\n    body: JSON.stringify(clientMetadata)\n  });\n  if (!response.ok) {\n    throw await parseErrorResponse(response);\n  }\n  return OAuthClientInformationFullSchema.parse(await response.json());\n}\nasync function auth(provider, options) {\n  var _a3, _b3;\n  try {\n    return await authInternal(provider, options);\n  } catch (error) {\n    if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {\n      await ((_a3 = provider.invalidateCredentials) == null ? void 0 : _a3.call(provider, \"all\"));\n      return await authInternal(provider, options);\n    } else if (error instanceof InvalidGrantError) {\n      await ((_b3 = provider.invalidateCredentials) == null ? void 0 : _b3.call(provider, \"tokens\"));\n      return await authInternal(provider, options);\n    }\n    throw error;\n  }\n}\nasync function selectResourceURL(serverUrl, provider, resourceMetadata) {\n  const defaultResource = resourceUrlFromServerUrl(serverUrl);\n  if (provider.validateResourceURL) {\n    return await provider.validateResourceURL(\n      defaultResource,\n      resourceMetadata == null ? void 0 : resourceMetadata.resource\n    );\n  }\n  if (!resourceMetadata) {\n    return void 0;\n  }\n  if (!checkResourceAllowed({\n    requestedResource: defaultResource,\n    configuredResource: resourceMetadata.resource\n  })) {\n    throw new Error(\n      `Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`\n    );\n  }\n  return new URL(resourceMetadata.resource);\n}\nasync function authInternal(provider, {\n  serverUrl,\n  authorizationCode,\n  callbackState,\n  scope,\n  resourceMetadataUrl,\n  fetchFn\n}) {\n  var _a3, _b3;\n  let resourceMetadata;\n  let authorizationServerUrl;\n  assertResourceMetadataUrlSameOrigin(serverUrl, resourceMetadataUrl);\n  try {\n    resourceMetadata = await discoverOAuthProtectedResourceMetadata(\n      serverUrl,\n      { resourceMetadataUrl },\n      fetchFn\n    );\n    if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {\n      authorizationServerUrl = resourceMetadata.authorization_servers[0];\n    }\n  } catch (e) {\n  }\n  if (!authorizationServerUrl) {\n    authorizationServerUrl = serverUrl;\n  }\n  const resource = await selectResourceURL(\n    serverUrl,\n    provider,\n    resourceMetadata\n  );\n  await ((_a3 = provider.validateAuthorizationServerURL) == null ? void 0 : _a3.call(\n    provider,\n    serverUrl,\n    authorizationServerUrl\n  ));\n  const metadata = await discoverAuthorizationServerMetadata(\n    authorizationServerUrl,\n    {\n      fetchFn\n    }\n  );\n  const currentAuthorizationServerInformation = createAuthorizationServerInformation(authorizationServerUrl, metadata);\n  let clientInformation = await Promise.resolve(provider.clientInformation());\n  if (!clientInformation) {\n    if (authorizationCode !== void 0) {\n      throw new Error(\n        \"Existing OAuth client information is required when exchanging an authorization code\"\n      );\n    }\n    if (!provider.saveClientInformation) {\n      throw new Error(\n        \"OAuth client information must be saveable for dynamic registration\"\n      );\n    }\n    const fullInformation = await registerClient(authorizationServerUrl, {\n      metadata,\n      clientMetadata: provider.clientMetadata,\n      fetchFn\n    });\n    clientInformation = addAuthorizationServerInformationToClientInformation(\n      fullInformation,\n      currentAuthorizationServerInformation\n    );\n    await provider.saveClientInformation(clientInformation);\n  }\n  if (authorizationCode !== void 0) {\n    if (provider.storedState) {\n      const expectedState = await provider.storedState();\n      if (expectedState !== void 0 && expectedState !== callbackState) {\n        throw new Error(\n          \"OAuth state parameter mismatch - possible CSRF attack\"\n        );\n      }\n    }\n    const storedAuthorizationServerInformation = await getStoredAuthorizationServerInformation({\n      provider,\n      clientInformation\n    });\n    if (!storedAuthorizationServerInformation) {\n      throw new MCPClientOAuthError({\n        message: \"Stored OAuth authorization server metadata is required when exchanging an authorization code\"\n      });\n    }\n    assertAuthorizationServerInformationMatches({\n      storedAuthorizationServerInformation,\n      currentAuthorizationServerInformation\n    });\n    const codeVerifier2 = await provider.codeVerifier();\n    const tokens2 = await exchangeAuthorization(authorizationServerUrl, {\n      metadata,\n      clientInformation,\n      authorizationCode,\n      codeVerifier: codeVerifier2,\n      redirectUri: provider.redirectUrl,\n      resource,\n      addClientAuthentication: provider.addClientAuthentication,\n      fetchFn\n    });\n    await provider.saveTokens(\n      addAuthorizationServerInformationToTokens(\n        tokens2,\n        currentAuthorizationServerInformation\n      )\n    );\n    return \"AUTHORIZED\";\n  }\n  const tokens = await provider.tokens();\n  if (tokens == null ? void 0 : tokens.refresh_token) {\n    const storedAuthorizationServerInformation = await getStoredAuthorizationServerInformation({\n      provider,\n      clientInformation,\n      tokens\n    });\n    if (storedAuthorizationServerInformation) {\n      assertAuthorizationServerInformationMatches({\n        storedAuthorizationServerInformation,\n        currentAuthorizationServerInformation\n      });\n    } else {\n      await ((_b3 = provider.invalidateCredentials) == null ? void 0 : _b3.call(provider, \"tokens\"));\n    }\n    try {\n      if (storedAuthorizationServerInformation) {\n        const newTokens = await refreshAuthorization(authorizationServerUrl, {\n          metadata,\n          clientInformation,\n          refreshToken: tokens.refresh_token,\n          resource,\n          addClientAuthentication: provider.addClientAuthentication,\n          fetchFn\n        });\n        await provider.saveTokens(\n          addAuthorizationServerInformationToTokens(\n            newTokens,\n            currentAuthorizationServerInformation\n          )\n        );\n        return \"AUTHORIZED\";\n      }\n    } catch (error) {\n      if (\n        // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.\n        !(error instanceof MCPClientOAuthError) || error instanceof ServerError\n      ) {\n      } else {\n        throw error;\n      }\n    }\n  }\n  const state = provider.state ? await provider.state() : void 0;\n  if (state && provider.saveState) {\n    await provider.saveState(state);\n  }\n  const { authorizationUrl, codeVerifier } = await startAuthorization(\n    authorizationServerUrl,\n    {\n      metadata,\n      clientInformation,\n      state,\n      redirectUrl: provider.redirectUrl,\n      scope: scope || provider.clientMetadata.scope,\n      resource\n    }\n  );\n  const savedAuthorizationServerInformation = await saveAuthorizationServerInformation({\n    provider,\n    clientInformation,\n    authorizationServerInformation: currentAuthorizationServerInformation\n  });\n  if (!savedAuthorizationServerInformation) {\n    throw new MCPClientOAuthError({\n      message: \"OAuth authorization server metadata must be saveable before starting authorization\"\n    });\n  }\n  await provider.saveCodeVerifier(codeVerifier);\n  await provider.redirectToAuthorization(authorizationUrl);\n  return \"REDIRECT\";\n}\n\n// src/tool/mcp-sse-transport.ts\nfunction isMessageEvent(event) {\n  return event === void 0 || event === \"message\";\n}\nvar SseMCPTransport = class {\n  constructor({\n    url,\n    headers,\n    authProvider,\n    redirect = \"error\",\n    fetch: fetchFn\n  }) {\n    this.connected = false;\n    this.url = new URL(url);\n    this.headers = headers;\n    this.authProvider = authProvider;\n    this.redirectMode = redirect;\n    this.fetchFn = fetchFn != null ? fetchFn : globalThis.fetch;\n  }\n  setProtocolVersion(version) {\n    this.protocolVersion = version;\n  }\n  async commonHeaders(base) {\n    var _a3;\n    const headers = {\n      ...this.headers,\n      ...base,\n      \"mcp-protocol-version\": (_a3 = this.protocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION\n    };\n    if (this.authProvider) {\n      const tokens = await this.authProvider.tokens();\n      if (tokens == null ? void 0 : tokens.access_token) {\n        headers[\"Authorization\"] = `Bearer ${tokens.access_token}`;\n      }\n    }\n    return withUserAgentSuffix(\n      headers,\n      `ai-sdk/${VERSION}`,\n      getRuntimeEnvironmentUserAgent()\n    );\n  }\n  async start() {\n    return new Promise((resolve, reject) => {\n      if (this.connected) {\n        return resolve();\n      }\n      this.abortController = new AbortController();\n      const establishConnection = async (triedAuth = false) => {\n        var _a3, _b3, _c, _d, _e;\n        try {\n          const headers = await this.commonHeaders({\n            Accept: \"text/event-stream\"\n          });\n          const response = await this.fetchFn(this.url.href, {\n            headers,\n            signal: (_a3 = this.abortController) == null ? void 0 : _a3.signal,\n            redirect: this.redirectMode\n          });\n          if (response.status === 401 && this.authProvider && !triedAuth) {\n            this.resourceMetadataUrl = extractResourceMetadataUrl(response);\n            try {\n              const result = await auth(this.authProvider, {\n                serverUrl: this.url,\n                resourceMetadataUrl: this.resourceMetadataUrl,\n                fetchFn: this.fetchFn\n              });\n              if (result !== \"AUTHORIZED\") {\n                const error = new UnauthorizedError();\n                (_b3 = this.onerror) == null ? void 0 : _b3.call(this, error);\n                return reject(error);\n              }\n            } catch (error) {\n              (_c = this.onerror) == null ? void 0 : _c.call(this, error);\n              return reject(error);\n            }\n            return establishConnection(true);\n          }\n          if (!response.ok || !response.body) {\n            let errorMessage = `MCP SSE Transport Error: ${response.status} ${response.statusText}`;\n            if (response.status === 405) {\n              errorMessage += \". This server does not support SSE transport. Try using `http` transport instead\";\n            }\n            const error = new MCPClientError({\n              message: errorMessage\n            });\n            (_d = this.onerror) == null ? void 0 : _d.call(this, error);\n            return reject(error);\n          }\n          const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());\n          const reader = stream.getReader();\n          const processEvents = async () => {\n            var _a4, _b4, _c2, _d2, _e2;\n            try {\n              while (true) {\n                const { done, value } = await reader.read();\n                if (done) {\n                  if (this.connected) {\n                    this.connected = false;\n                    throw new MCPClientError({\n                      message: \"MCP SSE Transport Error: Connection closed unexpectedly\"\n                    });\n                  }\n                  return;\n                }\n                const { event, data } = value;\n                if (event === \"endpoint\") {\n                  if (this.endpoint) {\n                    continue;\n                  }\n                  const endpoint = new URL(data, this.url);\n                  if (endpoint.origin !== this.url.origin) {\n                    this.connected = false;\n                    this.endpoint = void 0;\n                    (_a4 = this.sseConnection) == null ? void 0 : _a4.close();\n                    (_b4 = this.abortController) == null ? void 0 : _b4.abort();\n                    throw new MCPClientError({\n                      message: `MCP SSE Transport Error: Endpoint origin does not match connection origin: ${endpoint.origin}`\n                    });\n                  }\n                  this.endpoint = endpoint;\n                  this.connected = true;\n                  resolve();\n                } else if (isMessageEvent(event)) {\n                  try {\n                    const message = await parseJSONRPCMessage(data);\n                    (_c2 = this.onmessage) == null ? void 0 : _c2.call(this, message);\n                  } catch (error) {\n                    const e = new MCPClientError({\n                      message: \"MCP SSE Transport Error: Failed to parse message\",\n                      cause: error\n                    });\n                    (_d2 = this.onerror) == null ? void 0 : _d2.call(this, e);\n                  }\n                }\n              }\n            } catch (error) {\n              if (error instanceof Error && error.name === \"AbortError\") {\n                return;\n              }\n              (_e2 = this.onerror) == null ? void 0 : _e2.call(this, error);\n              reject(error);\n            }\n          };\n          this.sseConnection = {\n            close: () => reader.cancel()\n          };\n          processEvents();\n        } catch (error) {\n          if (error instanceof Error && error.name === \"AbortError\") {\n            return;\n          }\n          (_e = this.onerror) == null ? void 0 : _e.call(this, error);\n          reject(error);\n        }\n      };\n      void establishConnection();\n    });\n  }\n  async close() {\n    var _a3, _b3, _c;\n    this.connected = false;\n    this.endpoint = void 0;\n    (_a3 = this.sseConnection) == null ? void 0 : _a3.close();\n    (_b3 = this.abortController) == null ? void 0 : _b3.abort();\n    (_c = this.onclose) == null ? void 0 : _c.call(this);\n  }\n  async send(message) {\n    if (!this.endpoint || !this.connected) {\n      throw new MCPClientError({\n        message: \"MCP SSE Transport Error: Not connected\"\n      });\n    }\n    const endpoint = this.endpoint;\n    const attempt = async (triedAuth = false) => {\n      var _a3, _b3, _c, _d, _e;\n      try {\n        const headers = await this.commonHeaders({\n          \"Content-Type\": \"application/json\"\n        });\n        const init = {\n          method: \"POST\",\n          headers,\n          body: JSON.stringify(message),\n          signal: (_a3 = this.abortController) == null ? void 0 : _a3.signal,\n          redirect: this.redirectMode\n        };\n        const response = await this.fetchFn(endpoint.href, init);\n        if (response.status === 401 && this.authProvider && !triedAuth) {\n          this.resourceMetadataUrl = extractResourceMetadataUrl(response);\n          try {\n            const result = await auth(this.authProvider, {\n              serverUrl: this.url,\n              resourceMetadataUrl: this.resourceMetadataUrl,\n              fetchFn: this.fetchFn\n            });\n            if (result !== \"AUTHORIZED\") {\n              const error = new UnauthorizedError();\n              (_b3 = this.onerror) == null ? void 0 : _b3.call(this, error);\n              return;\n            }\n          } catch (error) {\n            (_c = this.onerror) == null ? void 0 : _c.call(this, error);\n            return;\n          }\n          return attempt(true);\n        }\n        if (!response.ok) {\n          const text = await response.text().catch(() => null);\n          const error = new MCPClientError({\n            message: `MCP SSE Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text}`\n          });\n          (_d = this.onerror) == null ? void 0 : _d.call(this, error);\n          return;\n        }\n      } catch (error) {\n        (_e = this.onerror) == null ? void 0 : _e.call(this, error);\n        return;\n      }\n    };\n    await attempt();\n  }\n};\n\n// src/tool/mcp-http-transport.ts\nimport {\n  EventSourceParserStream as EventSourceParserStream2,\n  withUserAgentSuffix as withUserAgentSuffix2,\n  getRuntimeEnvironmentUserAgent as getRuntimeEnvironmentUserAgent2\n} from \"@ai-sdk/provider-utils\";\nfunction isMessageEvent2(event) {\n  return event === void 0 || event === \"message\";\n}\nvar HttpMCPTransport = class {\n  constructor({\n    url,\n    headers,\n    authProvider,\n    redirect = \"error\",\n    initialSessionId,\n    initialProtocolVersion,\n    onSessionIdChange,\n    onSessionExpired,\n    terminateSessionOnClose = true,\n    fetch: fetchFn\n  }) {\n    this.inboundReconnectAttempts = 0;\n    this.reconnectionOptions = {\n      initialReconnectionDelay: 1e3,\n      maxReconnectionDelay: 3e4,\n      reconnectionDelayGrowFactor: 1.5,\n      maxRetries: 2\n    };\n    this.url = new URL(url);\n    this.headers = headers;\n    this.authProvider = authProvider;\n    this.redirectMode = redirect;\n    this.sessionId = initialSessionId;\n    this.protocolVersion = initialProtocolVersion;\n    this.onSessionIdChange = onSessionIdChange;\n    this.onSessionExpired = onSessionExpired;\n    this.terminateSessionOnClose = terminateSessionOnClose;\n    this.fetchFn = fetchFn != null ? fetchFn : globalThis.fetch;\n  }\n  setProtocolVersion(version) {\n    this.protocolVersion = version;\n  }\n  async commonHeaders({\n    base,\n    includeSessionId = true\n  }) {\n    var _a3;\n    const headers = {\n      ...this.headers,\n      ...base,\n      \"mcp-protocol-version\": (_a3 = this.protocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION\n    };\n    if (includeSessionId && this.sessionId) {\n      headers[\"mcp-session-id\"] = this.sessionId;\n    }\n    if (this.authProvider) {\n      const tokens = await this.authProvider.tokens();\n      if (tokens == null ? void 0 : tokens.access_token) {\n        headers[\"Authorization\"] = `Bearer ${tokens.access_token}`;\n      }\n    }\n    return withUserAgentSuffix2(\n      headers,\n      `ai-sdk/${VERSION}`,\n      getRuntimeEnvironmentUserAgent2()\n    );\n  }\n  setSessionId(sessionId) {\n    var _a3;\n    if (this.sessionId === sessionId) {\n      return;\n    }\n    this.sessionId = sessionId;\n    (_a3 = this.onSessionIdChange) == null ? void 0 : _a3.call(this, sessionId);\n  }\n  applySessionIdFromResponse(response) {\n    const sessionId = response.headers.get(\"mcp-session-id\");\n    if (sessionId) {\n      this.setSessionId(sessionId);\n    }\n  }\n  expireSessionId(sessionId) {\n    var _a3;\n    if (this.sessionId === sessionId) {\n      this.setSessionId(void 0);\n    }\n    (_a3 = this.onSessionExpired) == null ? void 0 : _a3.call(this, sessionId);\n  }\n  /**\n   * Runs a single OAuth recovery flow for concurrent 401 responses.\n   */\n  authorizeOnce(resourceMetadataUrl) {\n    if (!this.authProvider) {\n      return Promise.resolve(\"REDIRECT\");\n    }\n    if (!this.authPromise) {\n      this.authPromise = auth(this.authProvider, {\n        serverUrl: this.url,\n        resourceMetadataUrl,\n        fetchFn: this.fetchFn\n      }).finally(() => {\n        this.authPromise = void 0;\n      });\n    }\n    return this.authPromise;\n  }\n  async start() {\n    if (this.abortController) {\n      throw new MCPClientError({\n        message: \"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.\"\n      });\n    }\n    this.abortController = new AbortController();\n    void this.openInboundSse();\n  }\n  async close() {\n    var _a3, _b3, _c;\n    (_a3 = this.inboundSseConnection) == null ? void 0 : _a3.close();\n    try {\n      if (this.sessionId && this.terminateSessionOnClose && this.abortController && !this.abortController.signal.aborted) {\n        const headers = await this.commonHeaders({ base: {} });\n        await this.fetchFn(this.url.href, {\n          method: \"DELETE\",\n          headers,\n          signal: this.abortController.signal,\n          redirect: this.redirectMode\n        }).catch(() => void 0);\n      }\n    } catch (e) {\n    }\n    (_b3 = this.abortController) == null ? void 0 : _b3.abort();\n    (_c = this.onclose) == null ? void 0 : _c.call(this);\n  }\n  async send(message) {\n    const attempt = async (triedAuth = false) => {\n      var _a3, _b3, _c, _d, _e, _f, _g;\n      try {\n        const isInitializeRequest = \"method\" in message && message.method === \"initialize\";\n        const sessionIdForRequest = isInitializeRequest ? void 0 : this.sessionId;\n        const headers = await this.commonHeaders({\n          base: {\n            \"Content-Type\": \"application/json\",\n            Accept: \"application/json, text/event-stream\"\n          },\n          includeSessionId: !isInitializeRequest\n        });\n        const init = {\n          method: \"POST\",\n          headers,\n          body: JSON.stringify(message),\n          signal: (_a3 = this.abortController) == null ? void 0 : _a3.signal,\n          redirect: this.redirectMode\n        };\n        const response = await this.fetchFn(this.url.href, init);\n        this.applySessionIdFromResponse(response);\n        if (response.status === 401 && this.authProvider && !triedAuth) {\n          this.resourceMetadataUrl = extractResourceMetadataUrl(response);\n          try {\n            const result = await this.authorizeOnce(this.resourceMetadataUrl);\n            if (result !== \"AUTHORIZED\") {\n              const error2 = new UnauthorizedError();\n              throw error2;\n            }\n          } catch (error2) {\n            (_b3 = this.onerror) == null ? void 0 : _b3.call(this, error2);\n            throw error2;\n          }\n          return attempt(true);\n        }\n        if (response.status === 202) {\n          if (!this.inboundSseConnection) {\n            void this.openInboundSse();\n          }\n          return;\n        }\n        if (!response.ok) {\n          const text = await response.text().catch(() => null);\n          let errorMessage = `MCP HTTP Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text}`;\n          if (response.status === 404) {\n            if (sessionIdForRequest) {\n              this.expireSessionId(sessionIdForRequest);\n              errorMessage += \". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session\";\n            } else {\n              errorMessage += \". This server does not support HTTP transport. Try using `sse` transport instead\";\n            }\n          }\n          const error2 = new MCPClientError({\n            message: errorMessage,\n            statusCode: response.status,\n            url: this.url.href,\n            responseBody: text != null ? text : void 0\n          });\n          (_c = this.onerror) == null ? void 0 : _c.call(this, error2);\n          throw error2;\n        }\n        const isNotification = !(\"id\" in message);\n        if (isNotification) {\n          return;\n        }\n        const contentType = response.headers.get(\"content-type\") || \"\";\n        if (contentType.includes(\"application/json\")) {\n          const data = await response.json();\n          const messages = Array.isArray(data) ? data.map(\n            (message2) => JSONRPCMessageSchema.parse(message2)\n          ) : [JSONRPCMessageSchema.parse(data)];\n          for (const jsonRpcMessage of messages) {\n            (_d = this.onmessage) == null ? void 0 : _d.call(this, jsonRpcMessage);\n          }\n          return;\n        }\n        if (contentType.includes(\"text/event-stream\")) {\n          if (!response.body) {\n            const error2 = new MCPClientError({\n              message: \"MCP HTTP Transport Error: text/event-stream response without body\",\n              statusCode: response.status,\n              url: this.url.href\n            });\n            (_e = this.onerror) == null ? void 0 : _e.call(this, error2);\n            throw error2;\n          }\n          const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream2());\n          const reader = stream.getReader();\n          const processEvents = async () => {\n            var _a4, _b4, _c2;\n            try {\n              while (true) {\n                const { done, value } = await reader.read();\n                if (done) return;\n                const { event, data } = value;\n                if (isMessageEvent2(event)) {\n                  try {\n                    const jsonRpcMessage = await parseJSONRPCMessage(data);\n                    (_a4 = this.onmessage) == null ? void 0 : _a4.call(this, jsonRpcMessage);\n                  } catch (error2) {\n                    const e = new MCPClientError({\n                      message: \"MCP HTTP Transport Error: Failed to parse message\",\n                      cause: error2\n                    });\n                    (_b4 = this.onerror) == null ? void 0 : _b4.call(this, e);\n                  }\n                }\n              }\n            } catch (error2) {\n              if (error2 instanceof Error && error2.name === \"AbortError\") {\n                return;\n              }\n              (_c2 = this.onerror) == null ? void 0 : _c2.call(this, error2);\n            }\n          };\n          processEvents();\n          return;\n        }\n        const error = new MCPClientError({\n          message: `MCP HTTP Transport Error: Unexpected content type: ${contentType}`,\n          statusCode: response.status,\n          url: this.url.href\n        });\n        (_f = this.onerror) == null ? void 0 : _f.call(this, error);\n        throw error;\n      } catch (error) {\n        (_g = this.onerror) == null ? void 0 : _g.call(this, error);\n        throw error;\n      }\n    };\n    await attempt();\n  }\n  getNextReconnectionDelay(attempt) {\n    const {\n      initialReconnectionDelay,\n      reconnectionDelayGrowFactor,\n      maxReconnectionDelay\n    } = this.reconnectionOptions;\n    return Math.min(\n      initialReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, attempt),\n      maxReconnectionDelay\n    );\n  }\n  scheduleInboundSseReconnection() {\n    var _a3;\n    const { maxRetries } = this.reconnectionOptions;\n    if (maxRetries > 0 && this.inboundReconnectAttempts >= maxRetries) {\n      (_a3 = this.onerror) == null ? void 0 : _a3.call(\n        this,\n        new MCPClientError({\n          message: `MCP HTTP Transport Error: Maximum reconnection attempts (${maxRetries}) exceeded.`\n        })\n      );\n      return;\n    }\n    const delay = this.getNextReconnectionDelay(this.inboundReconnectAttempts);\n    this.inboundReconnectAttempts += 1;\n    setTimeout(async () => {\n      var _a4;\n      if ((_a4 = this.abortController) == null ? void 0 : _a4.signal.aborted) return;\n      await this.openInboundSse(false, this.lastInboundEventId);\n    }, delay);\n  }\n  // Open optional inbound SSE stream; best-effort and resumable\n  async openInboundSse(triedAuth = false, resumeToken) {\n    var _a3, _b3, _c, _d, _e, _f;\n    try {\n      const sessionIdForRequest = this.sessionId;\n      const headers = await this.commonHeaders({\n        base: {\n          Accept: \"text/event-stream\"\n        }\n      });\n      if (resumeToken) {\n        headers[\"last-event-id\"] = resumeToken;\n      }\n      const response = await this.fetchFn(this.url.href, {\n        method: \"GET\",\n        headers,\n        signal: (_a3 = this.abortController) == null ? void 0 : _a3.signal,\n        redirect: this.redirectMode\n      });\n      this.applySessionIdFromResponse(response);\n      if (response.status === 401 && this.authProvider && !triedAuth) {\n        this.resourceMetadataUrl = extractResourceMetadataUrl(response);\n        try {\n          const result = await this.authorizeOnce(this.resourceMetadataUrl);\n          if (result !== \"AUTHORIZED\") {\n            const error = new UnauthorizedError();\n            (_b3 = this.onerror) == null ? void 0 : _b3.call(this, error);\n            return;\n          }\n        } catch (error) {\n          (_c = this.onerror) == null ? void 0 : _c.call(this, error);\n          return;\n        }\n        return this.openInboundSse(true, resumeToken);\n      }\n      if (response.status === 405) {\n        return;\n      }\n      if (!response.ok || !response.body) {\n        if (response.status === 404 && sessionIdForRequest) {\n          this.expireSessionId(sessionIdForRequest);\n        }\n        const error = new MCPClientError({\n          message: `MCP HTTP Transport Error: GET SSE failed: ${response.status} ${response.statusText}`,\n          statusCode: response.status,\n          url: this.url.href\n        });\n        (_d = this.onerror) == null ? void 0 : _d.call(this, error);\n        return;\n      }\n      const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream2());\n      const reader = stream.getReader();\n      const processEvents = async () => {\n        var _a4, _b4, _c2, _d2;\n        try {\n          while (true) {\n            const { done, value } = await reader.read();\n            if (done) return;\n            const { event, data, id } = value;\n            if (id) {\n              this.lastInboundEventId = id;\n            }\n            if (isMessageEvent2(event)) {\n              try {\n                const jsonRpcMessage = await parseJSONRPCMessage(data);\n                (_a4 = this.onmessage) == null ? void 0 : _a4.call(this, jsonRpcMessage);\n              } catch (error) {\n                const e = new MCPClientError({\n                  message: \"MCP HTTP Transport Error: Failed to parse message\",\n                  cause: error\n                });\n                (_b4 = this.onerror) == null ? void 0 : _b4.call(this, e);\n              }\n            }\n          }\n        } catch (error) {\n          if (error instanceof Error && error.name === \"AbortError\") {\n            return;\n          }\n          (_c2 = this.onerror) == null ? void 0 : _c2.call(this, error);\n          if (!((_d2 = this.abortController) == null ? void 0 : _d2.signal.aborted)) {\n            this.scheduleInboundSseReconnection();\n          }\n        }\n      };\n      this.inboundSseConnection = {\n        close: () => reader.cancel()\n      };\n      this.inboundReconnectAttempts = 0;\n      processEvents();\n    } catch (error) {\n      if (error instanceof Error && error.name === \"AbortError\") {\n        return;\n      }\n      (_e = this.onerror) == null ? void 0 : _e.call(this, error);\n      if (!((_f = this.abortController) == null ? void 0 : _f.signal.aborted)) {\n        this.scheduleInboundSseReconnection();\n      }\n    }\n  }\n};\n\n// src/tool/mcp-transport.ts\nfunction createMcpTransport(config) {\n  switch (config.type) {\n    case \"sse\":\n      return new SseMCPTransport(config);\n    case \"http\":\n      return new HttpMCPTransport(config);\n    default:\n      throw new MCPClientError({\n        message: \"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.\"\n      });\n  }\n}\nfunction isCustomMcpTransport(transport) {\n  return \"start\" in transport && typeof transport.start === \"function\" && \"send\" in transport && typeof transport.send === \"function\" && \"close\" in transport && typeof transport.close === \"function\";\n}\n\n// src/tool/mcp-apps.ts\nimport { isJSONObject } from \"@ai-sdk/provider\";\nimport { convertBase64ToUint8Array } from \"@ai-sdk/provider-utils\";\nvar MCP_APP_EXTENSION_NAME = \"io.modelcontextprotocol/ui\";\nvar MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\";\nvar MCP_APP_LEGACY_RESOURCE_URI_META_KEY = \"ui/resourceUri\";\nvar mcpAppClientCapabilities = {\n  extensions: {\n    [MCP_APP_EXTENSION_NAME]: {\n      mimeTypes: [MCP_APP_MIME_TYPE]\n    }\n  }\n};\nfunction getToolUiMeta(meta) {\n  const uiMeta = meta == null ? void 0 : meta.ui;\n  return isJSONObject(uiMeta) ? uiMeta : void 0;\n}\nfunction getResourceUiMeta(meta) {\n  const resourceMeta = isJSONObject(meta) ? meta : void 0;\n  const rawUiMeta = resourceMeta == null ? void 0 : resourceMeta.ui;\n  const uiMeta = isJSONObject(rawUiMeta) ? rawUiMeta : void 0;\n  return uiMeta;\n}\nfunction parseVisibility(value) {\n  return Array.isArray(value) ? value.filter(\n    (v) => v === \"model\" || v === \"app\"\n  ) : void 0;\n}\nfunction getMCPAppToolMeta(tool2) {\n  var _a3, _b3;\n  const uiMeta = getToolUiMeta(tool2._meta);\n  const resourceUri = (_b3 = uiMeta == null ? void 0 : uiMeta.resourceUri) != null ? _b3 : (_a3 = tool2._meta) == null ? void 0 : _a3[MCP_APP_LEGACY_RESOURCE_URI_META_KEY];\n  const visibility = parseVisibility(uiMeta == null ? void 0 : uiMeta.visibility);\n  if (resourceUri !== void 0) {\n    if (typeof resourceUri !== \"string\" || !resourceUri.startsWith(\"ui://\")) {\n      throw new Error(\n        `Invalid MCP App resource URI: ${JSON.stringify(resourceUri)}`\n      );\n    }\n  } else if (uiMeta == null) {\n    return void 0;\n  }\n  return {\n    ...uiMeta,\n    ...resourceUri != null ? { resourceUri } : {},\n    ...visibility != null ? { visibility } : {}\n  };\n}\nfunction splitMCPAppTools(definitions) {\n  var _a3;\n  const modelVisibleTools = [];\n  const appVisibleTools = [];\n  for (const tool2 of definitions.tools) {\n    const visibility = (_a3 = getMCPAppToolMeta(tool2)) == null ? void 0 : _a3.visibility;\n    if (visibility == null || visibility.includes(\"model\")) {\n      modelVisibleTools.push(tool2);\n    }\n    if ((visibility == null ? void 0 : visibility.includes(\"app\")) === true) {\n      appVisibleTools.push(tool2);\n    }\n  }\n  return {\n    modelVisible: {\n      ...definitions,\n      tools: modelVisibleTools\n    },\n    appVisible: {\n      ...definitions,\n      tools: appVisibleTools\n    }\n  };\n}\nfunction getMCPAppResourceFromReadResult({\n  uri,\n  resource\n}) {\n  const content = resource.contents.find((content2) => content2.uri === uri);\n  if (content == null) {\n    throw new Error(`MCP App resource not found in read result: ${uri}`);\n  }\n  if (content.mimeType !== MCP_APP_MIME_TYPE) {\n    throw new Error(\n      `Unsupported MCP App resource MIME type: ${content.mimeType}`\n    );\n  }\n  const html = \"text\" in content && typeof content.text === \"string\" ? content.text : \"blob\" in content && typeof content.blob === \"string\" ? new TextDecoder().decode(convertBase64ToUint8Array(content.blob)) : void 0;\n  if (html == null) {\n    throw new Error(`Unsupported MCP App resource content format: ${uri}`);\n  }\n  const meta = getResourceUiMeta(content._meta);\n  return { uri, mimeType: MCP_APP_MIME_TYPE, html, meta };\n}\nasync function readMCPAppResource({\n  client,\n  uri,\n  options\n}) {\n  if (!uri.startsWith(\"ui://\")) {\n    throw new Error(`Unsupported MCP App resource URI: ${uri}`);\n  }\n  return getMCPAppResourceFromReadResult({\n    uri,\n    resource: await client.readResource({ uri, options })\n  });\n}\n\n// src/tool/mcp-client.ts\nvar CLIENT_VERSION = \"1.0.0\";\nfunction mcpToModelOutput({\n  output\n}) {\n  const result = output;\n  if (!(\"content\" in result) || !Array.isArray(result.content)) {\n    return { type: \"json\", value: result };\n  }\n  const convertedContent = result.content.map(\n    (part) => {\n      if (part.type === \"text\" && \"text\" in part) {\n        return { type: \"text\", text: part.text };\n      }\n      if (part.type === \"image\" && \"data\" in part && \"mimeType\" in part) {\n        return {\n          type: \"file\",\n          mediaType: part.mimeType,\n          data: { type: \"data\", data: part.data }\n        };\n      }\n      return { type: \"text\", text: JSON.stringify(part) };\n    }\n  );\n  return { type: \"content\", value: convertedContent };\n}\nasync function createMCPClient(config) {\n  const client = new DefaultMCPClient(config);\n  await client.init();\n  return client;\n}\nvar DefaultMCPClient = class {\n  constructor({\n    transport: transportConfig,\n    name: name3,\n    clientName = name3 != null ? name3 : \"ai-sdk-mcp-client\",\n    version = CLIENT_VERSION,\n    onUncaughtError,\n    capabilities,\n    initialInitializeResult\n  }) {\n    this.requestMessageId = 0;\n    this.responseHandlers = /* @__PURE__ */ new Map();\n    this.serverCapabilities = {};\n    this._serverInfo = { name: \"\", version: \"\" };\n    this._initializeResult = {\n      protocolVersion: LATEST_PROTOCOL_VERSION,\n      capabilities: {},\n      serverInfo: this._serverInfo\n    };\n    this.isClosed = true;\n    this.onUncaughtError = onUncaughtError;\n    this.clientCapabilities = capabilities != null ? capabilities : {};\n    this.initialInitializeResult = initialInitializeResult;\n    if (isCustomMcpTransport(transportConfig)) {\n      this.transport = transportConfig;\n    } else {\n      this.transport = createMcpTransport(transportConfig);\n    }\n    this.transport.onclose = () => this.onClose();\n    this.transport.onerror = (error) => this.onError(error);\n    this.transport.onmessage = (message) => {\n      if (\"method\" in message) {\n        if (\"id\" in message) {\n          this.onRequestMessage(message);\n        } else {\n          this.onError(\n            new MCPClientError({\n              message: \"Unsupported message type\"\n            })\n          );\n        }\n        return;\n      }\n      this.onResponse(message);\n    };\n    this.clientInfo = {\n      name: clientName,\n      version\n    };\n  }\n  get serverInfo() {\n    return this._serverInfo;\n  }\n  get initializeResult() {\n    return this._initializeResult;\n  }\n  get instructions() {\n    return this._serverInstructions;\n  }\n  async init() {\n    try {\n      await this.transport.start();\n      this.isClosed = false;\n      if (this.initialInitializeResult) {\n        const result2 = InitializeResultSchema.parse(\n          this.initialInitializeResult\n        );\n        this.applyInitializeResult(result2);\n        return this;\n      }\n      const result = await this.request({\n        request: {\n          method: \"initialize\",\n          params: {\n            protocolVersion: LATEST_PROTOCOL_VERSION,\n            capabilities: this.clientCapabilities,\n            clientInfo: this.clientInfo\n          }\n        },\n        resultSchema: InitializeResultSchema\n      });\n      if (result === void 0) {\n        throw new MCPClientError({\n          message: \"Server sent invalid initialize result\"\n        });\n      }\n      this.applyInitializeResult(result);\n      await this.notification({\n        method: \"notifications/initialized\"\n      });\n      return this;\n    } catch (error) {\n      await this.close();\n      throw error;\n    }\n  }\n  applyInitializeResult(result) {\n    if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {\n      throw new MCPClientError({\n        message: `Server's protocol version is not supported: ${result.protocolVersion}`\n      });\n    }\n    this.serverCapabilities = result.capabilities;\n    this._serverInfo = result.serverInfo;\n    this._initializeResult = result;\n    if (this.transport.setProtocolVersion) {\n      this.transport.setProtocolVersion(result.protocolVersion);\n    } else {\n      this.transport.protocolVersion = result.protocolVersion;\n    }\n    this._serverInstructions = result.instructions;\n  }\n  async close() {\n    var _a3;\n    if (this.isClosed) return;\n    await ((_a3 = this.transport) == null ? void 0 : _a3.close());\n    this.onClose();\n  }\n  assertCapability(method) {\n    switch (method) {\n      case \"initialize\":\n        break;\n      case \"completion/complete\":\n        if (!this.serverCapabilities.completions) {\n          throw new MCPClientError({\n            message: `Server does not support completions`\n          });\n        }\n        break;\n      case \"tools/list\":\n      case \"tools/call\":\n        if (!this.serverCapabilities.tools) {\n          throw new MCPClientError({\n            message: `Server does not support tools`\n          });\n        }\n        break;\n      case \"resources/list\":\n      case \"resources/read\":\n      case \"resources/templates/list\":\n        if (!this.serverCapabilities.resources) {\n          throw new MCPClientError({\n            message: `Server does not support resources`\n          });\n        }\n        break;\n      case \"prompts/list\":\n      case \"prompts/get\":\n        if (!this.serverCapabilities.prompts) {\n          throw new MCPClientError({\n            message: `Server does not support prompts`\n          });\n        }\n        break;\n      default:\n        throw new MCPClientError({\n          message: `Unsupported method: ${method}`\n        });\n    }\n  }\n  async request({\n    request,\n    resultSchema,\n    options\n  }) {\n    return new Promise((resolve, reject) => {\n      if (this.isClosed) {\n        return reject(\n          new MCPClientError({\n            message: \"Attempted to send a request from a closed client\"\n          })\n        );\n      }\n      this.assertCapability(request.method);\n      const signal = options == null ? void 0 : options.signal;\n      signal == null ? void 0 : signal.throwIfAborted();\n      const messageId = this.requestMessageId++;\n      const jsonrpcRequest = {\n        ...request,\n        jsonrpc: \"2.0\",\n        id: messageId\n      };\n      const cleanup = () => {\n        this.responseHandlers.delete(messageId);\n      };\n      this.responseHandlers.set(messageId, (response) => {\n        if (signal == null ? void 0 : signal.aborted) {\n          return reject(\n            new MCPClientError({\n              message: \"Request was aborted\",\n              cause: signal.reason\n            })\n          );\n        }\n        if (response instanceof Error) {\n          return reject(response);\n        }\n        try {\n          const result = resultSchema.parse(response.result);\n          resolve(result);\n        } catch (error) {\n          const parseError = new MCPClientError({\n            message: \"Failed to parse server response\",\n            cause: error\n          });\n          reject(parseError);\n        }\n      });\n      this.transport.send(jsonrpcRequest).catch((error) => {\n        cleanup();\n        reject(error);\n      });\n    });\n  }\n  async listTools({\n    params,\n    options\n  } = {}) {\n    return this.request({\n      request: { method: \"tools/list\", params },\n      resultSchema: ListToolsResultSchema,\n      options\n    });\n  }\n  async callTool({\n    name: name3,\n    arguments: args = {},\n    options\n  }) {\n    try {\n      return this.request({\n        request: { method: \"tools/call\", params: { name: name3, arguments: args } },\n        resultSchema: CallToolResultSchema,\n        options\n      });\n    } catch (error) {\n      throw error;\n    }\n  }\n  async listResourcesInternal({\n    params,\n    options\n  } = {}) {\n    try {\n      return this.request({\n        request: { method: \"resources/list\", params },\n        resultSchema: ListResourcesResultSchema,\n        options\n      });\n    } catch (error) {\n      throw error;\n    }\n  }\n  async readResourceInternal({\n    uri,\n    options\n  }) {\n    try {\n      return this.request({\n        request: { method: \"resources/read\", params: { uri } },\n        resultSchema: ReadResourceResultSchema,\n        options\n      });\n    } catch (error) {\n      throw error;\n    }\n  }\n  async listResourceTemplatesInternal({\n    options\n  } = {}) {\n    try {\n      return this.request({\n        request: { method: \"resources/templates/list\" },\n        resultSchema: ListResourceTemplatesResultSchema,\n        options\n      });\n    } catch (error) {\n      throw error;\n    }\n  }\n  async listPromptsInternal({\n    params,\n    options\n  } = {}) {\n    try {\n      return this.request({\n        request: { method: \"prompts/list\", params },\n        resultSchema: ListPromptsResultSchema,\n        options\n      });\n    } catch (error) {\n      throw error;\n    }\n  }\n  async getPromptInternal({\n    name: name3,\n    args,\n    options\n  }) {\n    try {\n      return this.request({\n        request: { method: \"prompts/get\", params: { name: name3, arguments: args } },\n        resultSchema: GetPromptResultSchema,\n        options\n      });\n    } catch (error) {\n      throw error;\n    }\n  }\n  async completeInternal({\n    options,\n    ...params\n  }) {\n    return this.request({\n      request: { method: \"completion/complete\", params },\n      resultSchema: CompleteResultSchema,\n      options\n    });\n  }\n  async notification(notification) {\n    const jsonrpcNotification = {\n      ...notification,\n      jsonrpc: \"2.0\"\n    };\n    await this.transport.send(jsonrpcNotification);\n  }\n  /**\n   * Returns a set of AI SDK tools from the MCP server.\n   * This fetches tool definitions and wraps them with execute functions.\n   * @returns A record of tool names to their implementations\n   */\n  async tools({\n    schemas = \"automatic\"\n  } = {}) {\n    const definitions = await this.listTools();\n    return this.toolsFromDefinitions(definitions, {\n      schemas\n    });\n  }\n  /**\n   * Creates AI SDK tools from tool definitions without fetching from the server.\n   */\n  toolsFromDefinitions(definitions, { schemas = \"automatic\" } = {}) {\n    var _a3, _b3;\n    const tools = {};\n    for (const {\n      name: name3,\n      title,\n      description,\n      inputSchema,\n      annotations,\n      _meta\n    } of definitions.tools) {\n      const resolvedTitle = title != null ? title : annotations == null ? void 0 : annotations.title;\n      if (schemas !== \"automatic\" && !Object.prototype.hasOwnProperty.call(schemas, name3)) {\n        continue;\n      }\n      const self = this;\n      const outputSchema = schemas !== \"automatic\" ? (_a3 = schemas[name3]) == null ? void 0 : _a3.outputSchema : void 0;\n      const appMeta = getMCPAppToolMeta({ _meta });\n      const metadata = {\n        clientName: this.clientInfo.name,\n        toolName: name3,\n        ...resolvedTitle != null ? { title: resolvedTitle } : {},\n        ...(appMeta == null ? void 0 : appMeta.resourceUri) != null ? {\n          app: {\n            ...appMeta,\n            mimeType: MCP_APP_MIME_TYPE\n          }\n        } : {}\n      };\n      const execute = async (args, options) => {\n        var _a4;\n        (_a4 = options == null ? void 0 : options.abortSignal) == null ? void 0 : _a4.throwIfAborted();\n        const result = await self.callTool({\n          name: name3,\n          arguments: args,\n          options: { signal: options == null ? void 0 : options.abortSignal }\n        });\n        if (result.isError) {\n          return result;\n        }\n        if (outputSchema != null) {\n          return self.extractStructuredContent(result, outputSchema, name3);\n        }\n        return result;\n      };\n      const toolWithExecute = schemas === \"automatic\" ? dynamicTool({\n        description,\n        title: resolvedTitle,\n        metadata,\n        inputSchema: jsonSchema({\n          ...inputSchema,\n          properties: (_b3 = inputSchema.properties) != null ? _b3 : {},\n          additionalProperties: false\n        }),\n        execute,\n        toModelOutput: mcpToModelOutput\n      }) : tool({\n        description,\n        title: resolvedTitle,\n        metadata,\n        inputSchema: schemas[name3].inputSchema,\n        ...outputSchema != null ? { outputSchema } : {},\n        execute,\n        toModelOutput: mcpToModelOutput\n      });\n      tools[name3] = { ...toolWithExecute, _meta };\n    }\n    return tools;\n  }\n  /**\n   * Extracts and validates structuredContent from a tool result.\n   */\n  async extractStructuredContent(result, outputSchema, toolName) {\n    if (\"structuredContent\" in result && result.structuredContent != null) {\n      const validationResult = await safeValidateTypes({\n        value: result.structuredContent,\n        schema: asSchema(outputSchema)\n      });\n      if (!validationResult.success) {\n        throw new MCPClientError({\n          message: `Tool \"${toolName}\" returned structuredContent that does not match the expected outputSchema`,\n          cause: validationResult.error\n        });\n      }\n      return validationResult.value;\n    }\n    if (\"content\" in result && Array.isArray(result.content)) {\n      const textContent = result.content.find((c) => c.type === \"text\");\n      if (textContent && \"text\" in textContent) {\n        const parseResult = await safeParseJSON({\n          text: textContent.text,\n          schema: outputSchema\n        });\n        if (!parseResult.success) {\n          throw new MCPClientError({\n            message: `Tool \"${toolName}\" returned content that does not match the expected outputSchema`,\n            cause: parseResult.error\n          });\n        }\n        return parseResult.value;\n      }\n    }\n    throw new MCPClientError({\n      message: `Tool \"${toolName}\" did not return structuredContent or parseable text content`\n    });\n  }\n  listResources({\n    params,\n    options\n  } = {}) {\n    return this.listResourcesInternal({ params, options });\n  }\n  readResource({\n    uri,\n    options\n  }) {\n    return this.readResourceInternal({ uri, options });\n  }\n  listResourceTemplates({\n    options\n  } = {}) {\n    return this.listResourceTemplatesInternal({ options });\n  }\n  experimental_listPrompts({\n    params,\n    options\n  } = {}) {\n    return this.listPromptsInternal({ params, options });\n  }\n  experimental_getPrompt({\n    name: name3,\n    arguments: args,\n    options\n  }) {\n    return this.getPromptInternal({ name: name3, args, options });\n  }\n  complete(args) {\n    return this.completeInternal(args);\n  }\n  onElicitationRequest(schema, handler) {\n    if (schema !== ElicitationRequestSchema) {\n      throw new MCPClientError({\n        message: \"Unsupported request schema. Only ElicitationRequestSchema is supported.\"\n      });\n    }\n    this.elicitationRequestHandler = handler;\n  }\n  async onRequestMessage(request) {\n    try {\n      if (request.method === \"ping\") {\n        await this.transport.send({\n          jsonrpc: \"2.0\",\n          id: request.id,\n          result: {}\n        });\n        return;\n      }\n      if (request.method !== \"elicitation/create\") {\n        await this.transport.send({\n          jsonrpc: \"2.0\",\n          id: request.id,\n          error: {\n            code: -32601,\n            message: `Unsupported request method: ${request.method}`\n          }\n        });\n        return;\n      }\n      if (!this.elicitationRequestHandler) {\n        await this.transport.send({\n          jsonrpc: \"2.0\",\n          id: request.id,\n          error: {\n            code: -32601,\n            message: \"No elicitation handler registered on client\"\n          }\n        });\n        return;\n      }\n      const parsedRequest = ElicitationRequestSchema.safeParse({\n        method: request.method,\n        params: request.params\n      });\n      if (!parsedRequest.success) {\n        await this.transport.send({\n          jsonrpc: \"2.0\",\n          id: request.id,\n          error: {\n            code: -32602,\n            message: `Invalid elicitation request: ${parsedRequest.error.message}`,\n            data: parsedRequest.error.issues\n          }\n        });\n        return;\n      }\n      try {\n        const result = await this.elicitationRequestHandler(parsedRequest.data);\n        const validatedResult = ElicitResultSchema.parse(result);\n        await this.transport.send({\n          jsonrpc: \"2.0\",\n          id: request.id,\n          result: validatedResult\n        });\n      } catch (error) {\n        await this.transport.send({\n          jsonrpc: \"2.0\",\n          id: request.id,\n          error: {\n            code: -32603,\n            message: error instanceof Error ? error.message : \"Failed to handle elicitation request\"\n          }\n        });\n        this.onError(error);\n      }\n    } catch (error) {\n      this.onError(error);\n    }\n  }\n  onClose() {\n    if (this.isClosed) return;\n    this.isClosed = true;\n    const error = new MCPClientError({\n      message: \"Connection closed\"\n    });\n    for (const handler of this.responseHandlers.values()) {\n      handler(error);\n    }\n    this.responseHandlers.clear();\n  }\n  onError(error) {\n    if (this.onUncaughtError) {\n      this.onUncaughtError(error);\n    }\n  }\n  onResponse(response) {\n    const messageId = Number(response.id);\n    const handler = this.responseHandlers.get(messageId);\n    if (handler === void 0) {\n      throw new MCPClientError({\n        message: `Protocol error: Received a response for an unknown message ID: ${JSON.stringify(\n          response\n        )}`\n      });\n    }\n    this.responseHandlers.delete(messageId);\n    handler(\n      \"result\" in response ? response : new MCPClientError({\n        message: response.error.message,\n        code: response.error.code,\n        data: response.error.data,\n        cause: response.error\n      })\n    );\n  }\n};\nexport {\n  ElicitResultSchema,\n  ElicitationRequestSchema,\n  MCP_APP_MIME_TYPE,\n  UnauthorizedError,\n  auth,\n  createMCPClient,\n  createMCPClient as experimental_createMCPClient,\n  mcpAppClientCapabilities,\n  readMCPAppResource,\n  splitMCPAppTools\n};\n//# sourceMappingURL=index.js.map","// src/tool/json-rpc-message.ts\nimport { parseJSON } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\n\n// src/tool/types.ts\nimport { z } from \"zod/v4\";\nvar ToolMetaSchema = z.optional(z.record(z.string(), z.unknown()));\nvar ClientOrServerImplementationSchema = z.looseObject({\n  name: z.string(),\n  version: z.string(),\n  title: z.optional(z.string())\n});\nvar BaseParamsSchema = z.looseObject({\n  _meta: z.optional(z.object({}).loose())\n});\nvar ResultSchema = BaseParamsSchema;\nvar RequestSchema = z.object({\n  method: z.string(),\n  params: z.optional(BaseParamsSchema)\n});\nvar ElicitationCapabilitySchema = z.object({\n  applyDefaults: z.optional(z.boolean())\n}).loose();\nvar ServerCapabilitiesSchema = z.looseObject({\n  experimental: z.optional(z.object({}).loose()),\n  logging: z.optional(z.object({}).loose()),\n  completions: z.optional(z.object({}).loose()),\n  prompts: z.optional(\n    z.looseObject({\n      listChanged: z.optional(z.boolean())\n    })\n  ),\n  resources: z.optional(\n    z.looseObject({\n      subscribe: z.optional(z.boolean()),\n      listChanged: z.optional(z.boolean())\n    })\n  ),\n  tools: z.optional(\n    z.looseObject({\n      listChanged: z.optional(z.boolean())\n    })\n  ),\n  elicitation: z.optional(ElicitationCapabilitySchema)\n});\nvar ClientCapabilitiesSchema = z.object({\n  elicitation: z.optional(ElicitationCapabilitySchema)\n}).loose();\nvar InitializeResultSchema = ResultSchema.extend({\n  protocolVersion: z.string(),\n  capabilities: ServerCapabilitiesSchema,\n  serverInfo: ClientOrServerImplementationSchema,\n  instructions: z.optional(z.string())\n});\nvar PaginatedResultSchema = ResultSchema.extend({\n  nextCursor: z.optional(z.string())\n});\nvar ToolSchema = z.object({\n  name: z.string(),\n  /**\n   * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool\n   */\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  inputSchema: z.object({\n    type: z.literal(\"object\"),\n    properties: z.optional(z.object({}).loose())\n  }).loose(),\n  /**\n   * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema\n   */\n  outputSchema: z.optional(z.object({}).loose()),\n  annotations: z.optional(\n    z.object({\n      title: z.optional(z.string())\n    }).loose()\n  ),\n  _meta: ToolMetaSchema\n}).loose();\nvar ListToolsResultSchema = PaginatedResultSchema.extend({\n  tools: z.array(ToolSchema)\n});\nvar TextContentSchema = z.object({\n  type: z.literal(\"text\"),\n  text: z.string()\n}).loose();\nvar ImageContentSchema = z.object({\n  type: z.literal(\"image\"),\n  data: z.base64(),\n  mimeType: z.string()\n}).loose();\nvar ResourceSchema = z.object({\n  uri: z.string(),\n  name: z.string(),\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  mimeType: z.optional(z.string()),\n  size: z.optional(z.number())\n}).loose();\nvar ListResourcesResultSchema = PaginatedResultSchema.extend({\n  resources: z.array(ResourceSchema)\n});\nvar ResourceContentsSchema = z.object({\n  /**\n   * The URI of this resource.\n   */\n  uri: z.string(),\n  /**\n   * Optional display name of the resource content.\n   */\n  name: z.optional(z.string()),\n  /**\n   * Optional human readable title.\n   */\n  title: z.optional(z.string()),\n  /**\n   * The MIME type of this resource, if known.\n   */\n  mimeType: z.optional(z.string())\n}).loose();\nvar TextResourceContentsSchema = ResourceContentsSchema.extend({\n  text: z.string()\n});\nvar BlobResourceContentsSchema = ResourceContentsSchema.extend({\n  blob: z.base64()\n});\nvar EmbeddedResourceSchema = z.object({\n  type: z.literal(\"resource\"),\n  resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])\n}).loose();\nvar ResourceLinkContentSchema = z.object({\n  type: z.literal(\"resource_link\"),\n  uri: z.string(),\n  name: z.string(),\n  description: z.optional(z.string()),\n  mimeType: z.optional(z.string())\n}).loose();\nvar CallToolResultSchema = ResultSchema.extend({\n  content: z.array(\n    z.union([\n      TextContentSchema,\n      ImageContentSchema,\n      EmbeddedResourceSchema,\n      ResourceLinkContentSchema\n    ])\n  ),\n  /**\n   * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content\n   */\n  structuredContent: z.optional(z.unknown()),\n  isError: z.boolean().default(false).optional()\n}).or(\n  ResultSchema.extend({\n    toolResult: z.unknown()\n  })\n);\nvar ResourceTemplateSchema = z.object({\n  uriTemplate: z.string(),\n  name: z.string(),\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  mimeType: z.optional(z.string())\n}).loose();\nvar ListResourceTemplatesResultSchema = ResultSchema.extend({\n  resourceTemplates: z.array(ResourceTemplateSchema)\n});\nvar ReadResourceResultSchema = ResultSchema.extend({\n  contents: z.array(\n    z.union([TextResourceContentsSchema, BlobResourceContentsSchema])\n  )\n});\nvar PromptReferenceSchema = z.object({\n  type: z.literal(\"ref/prompt\"),\n  name: z.string()\n}).loose();\nvar ResourceReferenceSchema = z.object({\n  type: z.literal(\"ref/resource\"),\n  uri: z.string()\n}).loose();\nvar CompletionArgumentSchema = z.object({\n  name: z.string(),\n  value: z.string()\n}).loose();\nvar CompleteRequestParamsSchema = BaseParamsSchema.extend({\n  ref: z.union([PromptReferenceSchema, ResourceReferenceSchema]),\n  argument: CompletionArgumentSchema,\n  context: z.optional(\n    z.object({\n      arguments: z.record(z.string(), z.string())\n    }).loose()\n  )\n});\nvar CompleteResultSchema = ResultSchema.extend({\n  completion: z.object({\n    values: z.array(z.string()).max(100),\n    total: z.optional(z.number().int()),\n    hasMore: z.optional(z.boolean())\n  }).loose()\n});\nvar PromptArgumentSchema = z.object({\n  name: z.string(),\n  description: z.optional(z.string()),\n  required: z.optional(z.boolean())\n}).loose();\nvar PromptSchema = z.object({\n  name: z.string(),\n  title: z.optional(z.string()),\n  description: z.optional(z.string()),\n  arguments: z.optional(z.array(PromptArgumentSchema))\n}).loose();\nvar ListPromptsResultSchema = PaginatedResultSchema.extend({\n  prompts: z.array(PromptSchema)\n});\nvar PromptMessageSchema = z.object({\n  role: z.union([z.literal(\"user\"), z.literal(\"assistant\")]),\n  content: z.union([\n    TextContentSchema,\n    ImageContentSchema,\n    EmbeddedResourceSchema,\n    ResourceLinkContentSchema\n  ])\n}).loose();\nvar GetPromptResultSchema = ResultSchema.extend({\n  description: z.optional(z.string()),\n  messages: z.array(PromptMessageSchema)\n});\nvar ElicitationRequestParamsSchema = BaseParamsSchema.extend({\n  message: z.string(),\n  requestedSchema: z.unknown()\n});\nvar ElicitationRequestSchema = RequestSchema.extend({\n  method: z.literal(\"elicitation/create\"),\n  params: ElicitationRequestParamsSchema\n});\nvar ElicitResultSchema = ResultSchema.extend({\n  action: z.union([\n    z.literal(\"accept\"),\n    z.literal(\"decline\"),\n    z.literal(\"cancel\")\n  ]),\n  content: z.optional(z.record(z.string(), z.unknown()))\n});\n\n// src/tool/json-rpc-message.ts\nvar JSONRPC_VERSION = \"2.0\";\nvar JSONRPCRequestSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION),\n  id: z2.union([z2.string(), z2.number().int()])\n}).merge(RequestSchema).strict();\nvar JSONRPCResponseSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION),\n  id: z2.union([z2.string(), z2.number().int()]),\n  result: ResultSchema\n}).strict();\nvar JSONRPCErrorSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION),\n  id: z2.union([z2.string(), z2.number().int()]),\n  error: z2.object({\n    code: z2.number().int(),\n    message: z2.string(),\n    data: z2.optional(z2.unknown())\n  })\n}).strict();\nvar JSONRPCNotificationSchema = z2.object({\n  jsonrpc: z2.literal(JSONRPC_VERSION)\n}).merge(\n  z2.object({\n    method: z2.string(),\n    params: z2.optional(BaseParamsSchema)\n  })\n).strict();\nvar JSONRPCMessageSchema = z2.union([\n  JSONRPCRequestSchema,\n  JSONRPCNotificationSchema,\n  JSONRPCResponseSchema,\n  JSONRPCErrorSchema\n]);\nasync function parseJSONRPCMessage(text) {\n  return JSONRPCMessageSchema.parse(await parseJSON({ text }));\n}\n\n// src/error/mcp-client-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_MCPClientError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar MCPClientError = class extends (_b = AISDKError, _a = symbol, _b) {\n  constructor({\n    name: name2 = \"MCPClientError\",\n    message,\n    cause,\n    data,\n    code,\n    statusCode,\n    url,\n    responseBody\n  }) {\n    super({ name: name2, message, cause });\n    this[_a] = true;\n    this.data = data;\n    this.code = code;\n    this.statusCode = statusCode;\n    this.url = url;\n    this.responseBody = responseBody;\n  }\n  static isInstance(error) {\n    return AISDKError.hasMarker(error, marker);\n  }\n};\n\n// src/tool/mcp-stdio/create-child-process.ts\nimport { spawn } from \"child_process\";\n\n// src/tool/mcp-stdio/get-environment.ts\nfunction getEnvironment(customEnv) {\n  const DEFAULT_INHERITED_ENV_VARS = globalThis.process.platform === \"win32\" ? [\n    \"APPDATA\",\n    \"HOMEDRIVE\",\n    \"HOMEPATH\",\n    \"LOCALAPPDATA\",\n    \"PATH\",\n    \"PROCESSOR_ARCHITECTURE\",\n    \"SYSTEMDRIVE\",\n    \"SYSTEMROOT\",\n    \"TEMP\",\n    \"USERNAME\",\n    \"USERPROFILE\"\n  ] : [\"HOME\", \"LOGNAME\", \"PATH\", \"SHELL\", \"TERM\", \"USER\"];\n  const env = customEnv ? { ...customEnv } : {};\n  for (const key of DEFAULT_INHERITED_ENV_VARS) {\n    const value = globalThis.process.env[key];\n    if (value === void 0) {\n      continue;\n    }\n    if (value.startsWith(\"()\")) {\n      continue;\n    }\n    env[key] = value;\n  }\n  return env;\n}\n\n// src/tool/mcp-stdio/create-child-process.ts\nfunction createChildProcess(config, signal) {\n  var _a2, _b2;\n  return spawn(config.command, (_a2 = config.args) != null ? _a2 : [], {\n    env: getEnvironment(config.env),\n    stdio: [\"pipe\", \"pipe\", (_b2 = config.stderr) != null ? _b2 : \"inherit\"],\n    shell: false,\n    signal,\n    windowsHide: globalThis.process.platform === \"win32\" && isElectron(),\n    cwd: config.cwd\n  });\n}\nfunction isElectron() {\n  return \"type\" in globalThis.process;\n}\n\n// src/tool/mcp-stdio/mcp-stdio-transport.ts\nvar StdioMCPTransport = class {\n  constructor(server) {\n    this.abortController = new AbortController();\n    this.readBuffer = new ReadBuffer();\n    this.serverParams = server;\n  }\n  async start() {\n    if (this.process) {\n      throw new MCPClientError({\n        message: \"StdioMCPTransport already started.\"\n      });\n    }\n    return new Promise((resolve, reject) => {\n      var _a2, _b2, _c, _d;\n      try {\n        const process = createChildProcess(\n          this.serverParams,\n          this.abortController.signal\n        );\n        this.process = process;\n        this.process.on(\"error\", (error) => {\n          var _a3, _b3;\n          if (error.name === \"AbortError\") {\n            (_a3 = this.onclose) == null ? void 0 : _a3.call(this);\n            return;\n          }\n          reject(error);\n          (_b3 = this.onerror) == null ? void 0 : _b3.call(this, error);\n        });\n        this.process.on(\"spawn\", () => {\n          resolve();\n        });\n        this.process.on(\"close\", (_code) => {\n          var _a3;\n          this.process = void 0;\n          (_a3 = this.onclose) == null ? void 0 : _a3.call(this);\n        });\n        (_a2 = this.process.stdin) == null ? void 0 : _a2.on(\"error\", (error) => {\n          var _a3;\n          (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error);\n        });\n        (_b2 = this.process.stdout) == null ? void 0 : _b2.on(\"data\", (chunk) => {\n          this.readBuffer.append(chunk);\n          void this.processReadBuffer();\n        });\n        (_c = this.process.stdout) == null ? void 0 : _c.on(\"error\", (error) => {\n          var _a3;\n          (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error);\n        });\n      } catch (error) {\n        reject(error);\n        (_d = this.onerror) == null ? void 0 : _d.call(this, error);\n      }\n    });\n  }\n  async processReadBuffer() {\n    var _a2, _b2;\n    while (true) {\n      const line = this.readBuffer.readLine();\n      if (line === null) {\n        break;\n      }\n      try {\n        const message = await deserializeMessage(line);\n        (_a2 = this.onmessage) == null ? void 0 : _a2.call(this, message);\n      } catch (error) {\n        (_b2 = this.onerror) == null ? void 0 : _b2.call(this, error);\n      }\n    }\n  }\n  async close() {\n    this.abortController.abort();\n    this.process = void 0;\n    this.readBuffer.clear();\n  }\n  send(message) {\n    return new Promise((resolve) => {\n      var _a2;\n      if (!((_a2 = this.process) == null ? void 0 : _a2.stdin)) {\n        throw new MCPClientError({\n          message: \"StdioClientTransport not connected\"\n        });\n      }\n      const json = serializeMessage(message);\n      if (this.process.stdin.write(json)) {\n        resolve();\n      } else {\n        this.process.stdin.once(\"drain\", resolve);\n      }\n    });\n  }\n};\nvar ReadBuffer = class {\n  append(chunk) {\n    this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk]) : chunk;\n  }\n  readLine() {\n    if (!this.buffer) return null;\n    const index = this.buffer.indexOf(\"\\n\");\n    if (index === -1) {\n      return null;\n    }\n    const line = this.buffer.toString(\"utf8\", 0, index);\n    this.buffer = this.buffer.subarray(index + 1);\n    return line;\n  }\n  clear() {\n    this.buffer = void 0;\n  }\n};\nfunction serializeMessage(message) {\n  return JSON.stringify(message) + \"\\n\";\n}\nasync function deserializeMessage(line) {\n  return parseJSONRPCMessage(line);\n}\nexport {\n  StdioMCPTransport as Experimental_StdioMCPTransport\n};\n//# sourceMappingURL=index.js.map","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n    /**\n     * Requested duration in milliseconds to retain task from creation.\n     */\n    ttl: z.number().optional(),\n    /**\n     * Time in milliseconds to wait between task status requests.\n     */\n    pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n    ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n    taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n    /**\n     * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n     */\n    progressToken: ProgressTokenSchema.optional(),\n    /**\n     * If specified, this request is related to the provided task.\n     */\n    [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n    /**\n     * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n     */\n    _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * If specified, the caller is requesting task-augmented execution for this request.\n     * The request will return a CreateTaskResult immediately, and the actual result can be\n     * retrieved later via tasks/result.\n     *\n     * Task augmentation is subject to capability negotiation - receivers MUST declare support\n     * for task augmentation of specific request types in their capabilities.\n     */\n    task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n    method: z.string(),\n    params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n    method: z.string(),\n    params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n    .object({\n    jsonrpc: z.literal(JSONRPC_VERSION),\n    id: RequestIdSchema,\n    ...RequestSchema.shape\n})\n    .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n    .object({\n    jsonrpc: z.literal(JSONRPC_VERSION),\n    ...NotificationSchema.shape\n})\n    .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n    .object({\n    jsonrpc: z.literal(JSONRPC_VERSION),\n    id: RequestIdSchema,\n    result: ResultSchema\n})\n    .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n    // SDK error codes\n    ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n    ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n    // Standard JSON-RPC error codes\n    ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n    ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n    ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n    ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n    ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n    // MCP-specific error codes\n    ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n    .object({\n    jsonrpc: z.literal(JSONRPC_VERSION),\n    id: RequestIdSchema.optional(),\n    error: z.object({\n        /**\n         * The error type that occurred.\n         */\n        code: z.number().int(),\n        /**\n         * A short description of the error. The message SHOULD be limited to a concise single sentence.\n         */\n        message: z.string(),\n        /**\n         * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n         */\n        data: z.unknown().optional()\n    })\n})\n    .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n    JSONRPCRequestSchema,\n    JSONRPCNotificationSchema,\n    JSONRPCResultResponseSchema,\n    JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The ID of the request to cancel.\n     *\n     * This MUST correspond to the ID of a request previously issued in the same direction.\n     */\n    requestId: RequestIdSchema.optional(),\n    /**\n     * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n     */\n    reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/cancelled'),\n    params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n    /**\n     * URL or data URI for the icon.\n     */\n    src: z.string(),\n    /**\n     * Optional MIME type for the icon.\n     */\n    mimeType: z.string().optional(),\n    /**\n     * Optional array of strings that specify sizes at which the icon can be used.\n     * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n     *\n     * If not provided, the client should assume that the icon can be used at any size.\n     */\n    sizes: z.array(z.string()).optional(),\n    /**\n     * Optional specifier for the theme this icon is designed for. `light` indicates\n     * the icon is designed to be used with a light background, and `dark` indicates\n     * the icon is designed to be used with a dark background.\n     *\n     * If not provided, the client should assume the icon can be used with any theme.\n     */\n    theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n    /**\n     * Optional set of sized icons that the client can display in a user interface.\n     *\n     * Clients that support rendering icons MUST support at least the following MIME types:\n     * - `image/png` - PNG images (safe, universal compatibility)\n     * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n     *\n     * Clients that support rendering icons SHOULD also support:\n     * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n     * - `image/webp` - WebP images (modern, efficient format)\n     */\n    icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n    /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n    name: z.string(),\n    /**\n     * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n     * even by those unfamiliar with domain-specific terminology.\n     *\n     * If not provided, the name should be used for display (except for Tool,\n     * where `annotations.title` should be given precedence over using `name`,\n     * if present).\n     */\n    title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    version: z.string(),\n    /**\n     * An optional URL of the website for this implementation.\n     */\n    websiteUrl: z.string().optional(),\n    /**\n     * An optional human-readable description of what this implementation does.\n     *\n     * This can be used by clients or servers to provide context about their purpose\n     * and capabilities. For example, a server might describe the types of resources\n     * or tools it provides, while a client might describe its intended use case.\n     */\n    description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n    applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n    if (value && typeof value === 'object' && !Array.isArray(value)) {\n        if (Object.keys(value).length === 0) {\n            return { form: {} };\n        }\n    }\n    return value;\n}, z.intersection(z.object({\n    form: FormElicitationCapabilitySchema.optional(),\n    url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n    /**\n     * Present if the client supports listing tasks.\n     */\n    list: AssertObjectSchema.optional(),\n    /**\n     * Present if the client supports cancelling tasks.\n     */\n    cancel: AssertObjectSchema.optional(),\n    /**\n     * Capabilities for task creation on specific request types.\n     */\n    requests: z\n        .looseObject({\n        /**\n         * Task support for sampling requests.\n         */\n        sampling: z\n            .looseObject({\n            createMessage: AssertObjectSchema.optional()\n        })\n            .optional(),\n        /**\n         * Task support for elicitation requests.\n         */\n        elicitation: z\n            .looseObject({\n            create: AssertObjectSchema.optional()\n        })\n            .optional()\n    })\n        .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n    /**\n     * Present if the server supports listing tasks.\n     */\n    list: AssertObjectSchema.optional(),\n    /**\n     * Present if the server supports cancelling tasks.\n     */\n    cancel: AssertObjectSchema.optional(),\n    /**\n     * Capabilities for task creation on specific request types.\n     */\n    requests: z\n        .looseObject({\n        /**\n         * Task support for tool requests.\n         */\n        tools: z\n            .looseObject({\n            call: AssertObjectSchema.optional()\n        })\n            .optional()\n    })\n        .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n    /**\n     * Experimental, non-standard capabilities that the client supports.\n     */\n    experimental: z.record(z.string(), AssertObjectSchema).optional(),\n    /**\n     * Present if the client supports sampling from an LLM.\n     */\n    sampling: z\n        .object({\n        /**\n         * Present if the client supports context inclusion via includeContext parameter.\n         * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n         */\n        context: AssertObjectSchema.optional(),\n        /**\n         * Present if the client supports tool use via tools and toolChoice parameters.\n         */\n        tools: AssertObjectSchema.optional()\n    })\n        .optional(),\n    /**\n     * Present if the client supports eliciting user input.\n     */\n    elicitation: ElicitationCapabilitySchema.optional(),\n    /**\n     * Present if the client supports listing roots.\n     */\n    roots: z\n        .object({\n        /**\n         * Whether the client supports issuing notifications for changes to the roots list.\n         */\n        listChanged: z.boolean().optional()\n    })\n        .optional(),\n    /**\n     * Present if the client supports task creation.\n     */\n    tasks: ClientTasksCapabilitySchema.optional(),\n    /**\n     * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n     */\n    extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n     */\n    protocolVersion: z.string(),\n    capabilities: ClientCapabilitiesSchema,\n    clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n    method: z.literal('initialize'),\n    params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n    /**\n     * Experimental, non-standard capabilities that the server supports.\n     */\n    experimental: z.record(z.string(), AssertObjectSchema).optional(),\n    /**\n     * Present if the server supports sending log messages to the client.\n     */\n    logging: AssertObjectSchema.optional(),\n    /**\n     * Present if the server supports sending completions to the client.\n     */\n    completions: AssertObjectSchema.optional(),\n    /**\n     * Present if the server offers any prompt templates.\n     */\n    prompts: z\n        .object({\n        /**\n         * Whether this server supports issuing notifications for changes to the prompt list.\n         */\n        listChanged: z.boolean().optional()\n    })\n        .optional(),\n    /**\n     * Present if the server offers any resources to read.\n     */\n    resources: z\n        .object({\n        /**\n         * Whether this server supports clients subscribing to resource updates.\n         */\n        subscribe: z.boolean().optional(),\n        /**\n         * Whether this server supports issuing notifications for changes to the resource list.\n         */\n        listChanged: z.boolean().optional()\n    })\n        .optional(),\n    /**\n     * Present if the server offers any tools to call.\n     */\n    tools: z\n        .object({\n        /**\n         * Whether this server supports issuing notifications for changes to the tool list.\n         */\n        listChanged: z.boolean().optional()\n    })\n        .optional(),\n    /**\n     * Present if the server supports task creation.\n     */\n    tasks: ServerTasksCapabilitySchema.optional(),\n    /**\n     * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n     */\n    extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n    /**\n     * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n     */\n    protocolVersion: z.string(),\n    capabilities: ServerCapabilitiesSchema,\n    serverInfo: ImplementationSchema,\n    /**\n     * Instructions describing how to use the server and its features.\n     *\n     * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n     */\n    instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/initialized'),\n    params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n    method: z.literal('ping'),\n    params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n    /**\n     * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n     */\n    progress: z.number(),\n    /**\n     * Total number of items to process (or total progress required), if known.\n     */\n    total: z.optional(z.number()),\n    /**\n     * An optional message describing the current progress.\n     */\n    message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n    ...NotificationsParamsSchema.shape,\n    ...ProgressSchema.shape,\n    /**\n     * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n     */\n    progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/progress'),\n    params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * An opaque token representing the current pagination position.\n     * If provided, the server should return results starting after this cursor.\n     */\n    cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n    params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n    /**\n     * An opaque token representing the pagination position after the last returned result.\n     * If present, there may be more results available.\n     */\n    nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n    taskId: z.string(),\n    status: TaskStatusSchema,\n    /**\n     * Time in milliseconds to keep task results available after completion.\n     * If null, the task has unlimited lifetime until manually cleaned up.\n     */\n    ttl: z.union([z.number(), z.null()]),\n    /**\n     * ISO 8601 timestamp when the task was created.\n     */\n    createdAt: z.string(),\n    /**\n     * ISO 8601 timestamp when the task was last updated.\n     */\n    lastUpdatedAt: z.string(),\n    pollInterval: z.optional(z.number()),\n    /**\n     * Optional diagnostic message for failed tasks or other status information.\n     */\n    statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n    task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/tasks/status'),\n    params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n    method: z.literal('tasks/get'),\n    params: BaseRequestParamsSchema.extend({\n        taskId: z.string()\n    })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n    method: z.literal('tasks/result'),\n    params: BaseRequestParamsSchema.extend({\n        taskId: z.string()\n    })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n    tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n    method: z.literal('tasks/cancel'),\n    params: BaseRequestParamsSchema.extend({\n        taskId: z.string()\n    })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n    /**\n     * The URI of this resource.\n     */\n    uri: z.string(),\n    /**\n     * The MIME type of this resource, if known.\n     */\n    mimeType: z.optional(z.string()),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n    /**\n     * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n     */\n    text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n    try {\n        // atob throws a DOMException if the string contains characters\n        // that are not part of the Base64 character set.\n        atob(val);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n    /**\n     * A base64-encoded string representing the binary data of the item.\n     */\n    blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n    /**\n     * Intended audience(s) for the resource.\n     */\n    audience: z.array(RoleSchema).optional(),\n    /**\n     * Importance hint for the resource, from 0 (least) to 1 (most).\n     */\n    priority: z.number().min(0).max(1).optional(),\n    /**\n     * ISO 8601 timestamp for the most recent modification.\n     */\n    lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * The URI of this resource.\n     */\n    uri: z.string(),\n    /**\n     * A description of what this resource represents.\n     *\n     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n     */\n    description: z.optional(z.string()),\n    /**\n     * The MIME type of this resource, if known.\n     */\n    mimeType: z.optional(z.string()),\n    /**\n     * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n     *\n     * This can be used by Hosts to display file sizes and estimate context window usage.\n     */\n    size: z.optional(z.number()),\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n     */\n    uriTemplate: z.string(),\n    /**\n     * A description of what this template is for.\n     *\n     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n     */\n    description: z.optional(z.string()),\n    /**\n     * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n     */\n    mimeType: z.optional(z.string()),\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n    resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n    resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n     *\n     * @format uri\n     */\n    uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n    method: z.literal('resources/read'),\n    params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n    contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/resources/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n    method: z.literal('resources/subscribe'),\n    params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n    method: z.literal('resources/unsubscribe'),\n    params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n     */\n    uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/resources/updated'),\n    params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n    /**\n     * The name of the argument.\n     */\n    name: z.string(),\n    /**\n     * A human-readable description of the argument.\n     */\n    description: z.optional(z.string()),\n    /**\n     * Whether this argument must be provided.\n     */\n    required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * An optional description of what this prompt provides\n     */\n    description: z.optional(z.string()),\n    /**\n     * A list of arguments to use for templating the prompt.\n     */\n    arguments: z.optional(z.array(PromptArgumentSchema)),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n    prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The name of the prompt or prompt template.\n     */\n    name: z.string(),\n    /**\n     * Arguments to use for templating the prompt.\n     */\n    arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n    method: z.literal('prompts/get'),\n    params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n    type: z.literal('text'),\n    /**\n     * The text content of the message.\n     */\n    text: z.string(),\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n    type: z.literal('image'),\n    /**\n     * The base64-encoded image data.\n     */\n    data: Base64Schema,\n    /**\n     * The MIME type of the image. Different providers may support different image types.\n     */\n    mimeType: z.string(),\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n    type: z.literal('audio'),\n    /**\n     * The base64-encoded audio data.\n     */\n    data: Base64Schema,\n    /**\n     * The MIME type of the audio. Different providers may support different audio types.\n     */\n    mimeType: z.string(),\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n    type: z.literal('tool_use'),\n    /**\n     * The name of the tool to invoke.\n     * Must match a tool name from the request's tools array.\n     */\n    name: z.string(),\n    /**\n     * Unique identifier for this tool call.\n     * Used to correlate with ToolResultContent in subsequent messages.\n     */\n    id: z.string(),\n    /**\n     * Arguments to pass to the tool.\n     * Must conform to the tool's inputSchema.\n     */\n    input: z.record(z.string(), z.unknown()),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n    type: z.literal('resource'),\n    resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n    /**\n     * Optional annotations for the client.\n     */\n    annotations: AnnotationsSchema.optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n    type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n    TextContentSchema,\n    ImageContentSchema,\n    AudioContentSchema,\n    ResourceLinkSchema,\n    EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n    role: RoleSchema,\n    content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n    /**\n     * An optional description for the prompt.\n     */\n    description: z.string().optional(),\n    messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/prompts/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n    /**\n     * A human-readable title for the tool.\n     */\n    title: z.string().optional(),\n    /**\n     * If true, the tool does not modify its environment.\n     *\n     * Default: false\n     */\n    readOnlyHint: z.boolean().optional(),\n    /**\n     * If true, the tool may perform destructive updates to its environment.\n     * If false, the tool performs only additive updates.\n     *\n     * (This property is meaningful only when `readOnlyHint == false`)\n     *\n     * Default: true\n     */\n    destructiveHint: z.boolean().optional(),\n    /**\n     * If true, calling the tool repeatedly with the same arguments\n     * will have no additional effect on the its environment.\n     *\n     * (This property is meaningful only when `readOnlyHint == false`)\n     *\n     * Default: false\n     */\n    idempotentHint: z.boolean().optional(),\n    /**\n     * If true, this tool may interact with an \"open world\" of external\n     * entities. If false, the tool's domain of interaction is closed.\n     * For example, the world of a web search tool is open, whereas that\n     * of a memory tool is not.\n     *\n     * Default: true\n     */\n    openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n    /**\n     * Indicates the tool's preference for task-augmented execution.\n     * - \"required\": Clients MUST invoke the tool as a task\n     * - \"optional\": Clients MAY invoke the tool as a task or normal request\n     * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n     *\n     * If not present, defaults to \"forbidden\".\n     */\n    taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n    ...BaseMetadataSchema.shape,\n    ...IconsSchema.shape,\n    /**\n     * A human-readable description of the tool.\n     */\n    description: z.string().optional(),\n    /**\n     * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n     * Must have type: 'object' at the root level per MCP spec.\n     */\n    inputSchema: z\n        .object({\n        type: z.literal('object'),\n        properties: z.record(z.string(), AssertObjectSchema).optional(),\n        required: z.array(z.string()).optional()\n    })\n        .catchall(z.unknown()),\n    /**\n     * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n     * returned in the structuredContent field of a CallToolResult.\n     * Must have type: 'object' at the root level per MCP spec.\n     */\n    outputSchema: z\n        .object({\n        type: z.literal('object'),\n        properties: z.record(z.string(), AssertObjectSchema).optional(),\n        required: z.array(z.string()).optional()\n    })\n        .catchall(z.unknown())\n        .optional(),\n    /**\n     * Optional additional tool information.\n     */\n    annotations: ToolAnnotationsSchema.optional(),\n    /**\n     * Execution-related properties for this tool.\n     */\n    execution: ToolExecutionSchema.optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n    method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n    tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n    /**\n     * A list of content objects that represent the result of the tool call.\n     *\n     * If the Tool does not define an outputSchema, this field MUST be present in the result.\n     * For backwards compatibility, this field is always present, but it may be empty.\n     */\n    content: z.array(ContentBlockSchema).default([]),\n    /**\n     * An object containing structured tool output.\n     *\n     * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n     */\n    structuredContent: z.record(z.string(), z.unknown()).optional(),\n    /**\n     * Whether the tool call ended in an error.\n     *\n     * If not set, this is assumed to be false (the call was successful).\n     *\n     * Any errors that originate from the tool SHOULD be reported inside the result\n     * object, with `isError` set to true, _not_ as an MCP protocol-level error\n     * response. Otherwise, the LLM would not be able to see that an error occurred\n     * and self-correct.\n     *\n     * However, any errors in _finding_ the tool, an error indicating that the\n     * server does not support tool calls, or any other exceptional conditions,\n     * should be reported as an MCP error response.\n     */\n    isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n    toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    /**\n     * The name of the tool to call.\n     */\n    name: z.string(),\n    /**\n     * Arguments to pass to the tool.\n     */\n    arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n    method: z.literal('tools/call'),\n    params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/tools/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n    /**\n     * If true, the list will be refreshed automatically when a list changed notification is received.\n     * The callback will be called with the updated list.\n     *\n     * If false, the callback will be called with null items, allowing manual refresh.\n     *\n     * @default true\n     */\n    autoRefresh: z.boolean().default(true),\n    /**\n     * Debounce time in milliseconds for list changed notification processing.\n     *\n     * Multiple notifications received within this timeframe will only trigger one refresh.\n     * Set to 0 to disable debouncing.\n     *\n     * @default 300\n     */\n    debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n    /**\n     * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n     */\n    level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n    method: z.literal('logging/setLevel'),\n    params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The severity of this log message.\n     */\n    level: LoggingLevelSchema,\n    /**\n     * An optional name of the logger issuing this message.\n     */\n    logger: z.string().optional(),\n    /**\n     * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n     */\n    data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/message'),\n    params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n    /**\n     * A hint for a model name.\n     */\n    name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n    /**\n     * Optional hints to use for model selection.\n     */\n    hints: z.array(ModelHintSchema).optional(),\n    /**\n     * How much to prioritize cost when selecting a model.\n     */\n    costPriority: z.number().min(0).max(1).optional(),\n    /**\n     * How much to prioritize sampling speed (latency) when selecting a model.\n     */\n    speedPriority: z.number().min(0).max(1).optional(),\n    /**\n     * How much to prioritize intelligence and capabilities when selecting a model.\n     */\n    intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n    /**\n     * Controls when tools are used:\n     * - \"auto\": Model decides whether to use tools (default)\n     * - \"required\": Model MUST use at least one tool before completing\n     * - \"none\": Model MUST NOT use any tools\n     */\n    mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n    type: z.literal('tool_result'),\n    toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n    content: z.array(ContentBlockSchema).default([]),\n    structuredContent: z.object({}).loose().optional(),\n    isError: z.boolean().optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n    TextContentSchema,\n    ImageContentSchema,\n    AudioContentSchema,\n    ToolUseContentSchema,\n    ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n    role: RoleSchema,\n    content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    messages: z.array(SamplingMessageSchema),\n    /**\n     * The server's preferences for which model to select. The client MAY modify or omit this request.\n     */\n    modelPreferences: ModelPreferencesSchema.optional(),\n    /**\n     * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n     */\n    systemPrompt: z.string().optional(),\n    /**\n     * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n     * The client MAY ignore this request.\n     *\n     * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n     * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n     */\n    includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n    temperature: z.number().optional(),\n    /**\n     * The requested maximum number of tokens to sample (to prevent runaway completions).\n     *\n     * The client MAY choose to sample fewer tokens than the requested maximum.\n     */\n    maxTokens: z.number().int(),\n    stopSequences: z.array(z.string()).optional(),\n    /**\n     * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n     */\n    metadata: AssertObjectSchema.optional(),\n    /**\n     * Tools that the model may use during generation.\n     * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n     */\n    tools: z.array(ToolSchema).optional(),\n    /**\n     * Controls how the model uses tools.\n     * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n     * Default is `{ mode: \"auto\" }`.\n     */\n    toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n    method: z.literal('sampling/createMessage'),\n    params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n    /**\n     * The name of the model that generated the message.\n     */\n    model: z.string(),\n    /**\n     * The reason why sampling stopped, if known.\n     *\n     * Standard values:\n     * - \"endTurn\": Natural end of the assistant's turn\n     * - \"stopSequence\": A stop sequence was encountered\n     * - \"maxTokens\": Maximum token limit was reached\n     *\n     * This field is an open string to allow for provider-specific stop reasons.\n     */\n    stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n    role: RoleSchema,\n    /**\n     * Response content. Single content block (text, image, or audio).\n     */\n    content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n    /**\n     * The name of the model that generated the message.\n     */\n    model: z.string(),\n    /**\n     * The reason why sampling stopped, if known.\n     *\n     * Standard values:\n     * - \"endTurn\": Natural end of the assistant's turn\n     * - \"stopSequence\": A stop sequence was encountered\n     * - \"maxTokens\": Maximum token limit was reached\n     * - \"toolUse\": The model wants to use one or more tools\n     *\n     * This field is an open string to allow for provider-specific stop reasons.\n     */\n    stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n    role: RoleSchema,\n    /**\n     * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n     */\n    content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n    type: z.literal('boolean'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minLength: z.number().optional(),\n    maxLength: z.number().optional(),\n    format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n    default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n    type: z.enum(['number', 'integer']),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minimum: z.number().optional(),\n    maximum: z.number().optional(),\n    default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    enum: z.array(z.string()),\n    default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    oneOf: z.array(z.object({\n        const: z.string(),\n        title: z.string()\n    })),\n    default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n    type: z.literal('string'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    enum: z.array(z.string()),\n    enumNames: z.array(z.string()).optional(),\n    default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n    type: z.literal('array'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minItems: z.number().optional(),\n    maxItems: z.number().optional(),\n    items: z.object({\n        type: z.literal('string'),\n        enum: z.array(z.string())\n    }),\n    default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n    type: z.literal('array'),\n    title: z.string().optional(),\n    description: z.string().optional(),\n    minItems: z.number().optional(),\n    maxItems: z.number().optional(),\n    items: z.object({\n        anyOf: z.array(z.object({\n            const: z.string(),\n            title: z.string()\n        }))\n    }),\n    default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    /**\n     * The elicitation mode.\n     *\n     * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n     */\n    mode: z.literal('form').optional(),\n    /**\n     * The message to present to the user describing what information is being requested.\n     */\n    message: z.string(),\n    /**\n     * A restricted subset of JSON Schema.\n     * Only top-level properties are allowed, without nesting.\n     */\n    requestedSchema: z.object({\n        type: z.literal('object'),\n        properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n        required: z.array(z.string()).optional()\n    })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n    /**\n     * The elicitation mode.\n     */\n    mode: z.literal('url'),\n    /**\n     * The message to present to the user explaining why the interaction is needed.\n     */\n    message: z.string(),\n    /**\n     * The ID of the elicitation, which must be unique within the context of the server.\n     * The client MUST treat this ID as an opaque value.\n     */\n    elicitationId: z.string(),\n    /**\n     * The URL that the user should navigate to.\n     */\n    url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n    method: z.literal('elicitation/create'),\n    params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n    /**\n     * The ID of the elicitation that completed.\n     */\n    elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/elicitation/complete'),\n    params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n    /**\n     * The user action in response to the elicitation.\n     * - \"accept\": User submitted the form/confirmed the action\n     * - \"decline\": User explicitly decline the action\n     * - \"cancel\": User dismissed without making an explicit choice\n     */\n    action: z.enum(['accept', 'decline', 'cancel']),\n    /**\n     * The submitted form data, only present when action is \"accept\".\n     * Contains values matching the requested schema.\n     * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n     * We normalize null to undefined for leniency while maintaining type compatibility.\n     */\n    content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n    type: z.literal('ref/resource'),\n    /**\n     * The URI or URI template of the resource.\n     */\n    uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n    type: z.literal('ref/prompt'),\n    /**\n     * The name of the prompt or prompt template\n     */\n    name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n    ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n    /**\n     * The argument's information\n     */\n    argument: z.object({\n        /**\n         * The name of the argument\n         */\n        name: z.string(),\n        /**\n         * The value of the argument to use for completion matching.\n         */\n        value: z.string()\n    }),\n    context: z\n        .object({\n        /**\n         * Previously-resolved variables in a URI template or prompt.\n         */\n        arguments: z.record(z.string(), z.string()).optional()\n    })\n        .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n    method: z.literal('completion/complete'),\n    params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n    if (request.params.ref.type !== 'ref/prompt') {\n        throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n    }\n    void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n    if (request.params.ref.type !== 'ref/resource') {\n        throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n    }\n    void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n    completion: z.looseObject({\n        /**\n         * An array of completion values. Must not exceed 100 items.\n         */\n        values: z.array(z.string()).max(100),\n        /**\n         * The total number of completion options available. This can exceed the number of values actually sent in the response.\n         */\n        total: z.optional(z.number().int()),\n        /**\n         * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n         */\n        hasMore: z.optional(z.boolean())\n    })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n    /**\n     * The URI identifying the root. This *must* start with file:// for now.\n     */\n    uri: z.string().startsWith('file://'),\n    /**\n     * An optional name for the root.\n     */\n    name: z.string().optional(),\n    /**\n     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n     * for notes on _meta usage.\n     */\n    _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n    method: z.literal('roots/list'),\n    params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n    roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n    method: z.literal('notifications/roots/list_changed'),\n    params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n    PingRequestSchema,\n    InitializeRequestSchema,\n    CompleteRequestSchema,\n    SetLevelRequestSchema,\n    GetPromptRequestSchema,\n    ListPromptsRequestSchema,\n    ListResourcesRequestSchema,\n    ListResourceTemplatesRequestSchema,\n    ReadResourceRequestSchema,\n    SubscribeRequestSchema,\n    UnsubscribeRequestSchema,\n    CallToolRequestSchema,\n    ListToolsRequestSchema,\n    GetTaskRequestSchema,\n    GetTaskPayloadRequestSchema,\n    ListTasksRequestSchema,\n    CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n    CancelledNotificationSchema,\n    ProgressNotificationSchema,\n    InitializedNotificationSchema,\n    RootsListChangedNotificationSchema,\n    TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n    EmptyResultSchema,\n    CreateMessageResultSchema,\n    CreateMessageResultWithToolsSchema,\n    ElicitResultSchema,\n    ListRootsResultSchema,\n    GetTaskResultSchema,\n    ListTasksResultSchema,\n    CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n    PingRequestSchema,\n    CreateMessageRequestSchema,\n    ElicitRequestSchema,\n    ListRootsRequestSchema,\n    GetTaskRequestSchema,\n    GetTaskPayloadRequestSchema,\n    ListTasksRequestSchema,\n    CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n    CancelledNotificationSchema,\n    ProgressNotificationSchema,\n    LoggingMessageNotificationSchema,\n    ResourceUpdatedNotificationSchema,\n    ResourceListChangedNotificationSchema,\n    ToolListChangedNotificationSchema,\n    PromptListChangedNotificationSchema,\n    TaskStatusNotificationSchema,\n    ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n    EmptyResultSchema,\n    InitializeResultSchema,\n    CompleteResultSchema,\n    GetPromptResultSchema,\n    ListPromptsResultSchema,\n    ListResourcesResultSchema,\n    ListResourceTemplatesResultSchema,\n    ReadResourceResultSchema,\n    CallToolResultSchema,\n    ListToolsResultSchema,\n    GetTaskResultSchema,\n    ListTasksResultSchema,\n    CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n    constructor(code, message, data) {\n        super(`MCP error ${code}: ${message}`);\n        this.code = code;\n        this.data = data;\n        this.name = 'McpError';\n    }\n    /**\n     * Factory method to create the appropriate error type based on the error code and data\n     */\n    static fromError(code, message, data) {\n        // Check for specific error types\n        if (code === ErrorCode.UrlElicitationRequired && data) {\n            const errorData = data;\n            if (errorData.elicitations) {\n                return new UrlElicitationRequiredError(errorData.elicitations, message);\n            }\n        }\n        // Default to generic McpError\n        return new McpError(code, message, data);\n    }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n    constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n        super(ErrorCode.UrlElicitationRequired, message, {\n            elicitations: elicitations\n        });\n    }\n    get elicitations() {\n        return this.data?.elicitations ?? [];\n    }\n}\n//# sourceMappingURL=types.js.map","import * as z from 'zod/v4';\n/**\n * Reusable URL validation that disallows javascript: scheme\n */\nexport const SafeUrlSchema = z\n    .url()\n    .superRefine((val, ctx) => {\n    if (!URL.canParse(val)) {\n        ctx.addIssue({\n            code: z.ZodIssueCode.custom,\n            message: 'URL must be parseable',\n            fatal: true\n        });\n        return z.NEVER;\n    }\n})\n    .refine(url => {\n    const u = new URL(url);\n    return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' });\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n    resource: z.string().url(),\n    authorization_servers: z.array(SafeUrlSchema).optional(),\n    jwks_uri: z.string().url().optional(),\n    scopes_supported: z.array(z.string()).optional(),\n    bearer_methods_supported: z.array(z.string()).optional(),\n    resource_signing_alg_values_supported: z.array(z.string()).optional(),\n    resource_name: z.string().optional(),\n    resource_documentation: z.string().optional(),\n    resource_policy_uri: z.string().url().optional(),\n    resource_tos_uri: z.string().url().optional(),\n    tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n    authorization_details_types_supported: z.array(z.string()).optional(),\n    dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n    dpop_bound_access_tokens_required: z.boolean().optional()\n});\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n    issuer: z.string(),\n    authorization_endpoint: SafeUrlSchema,\n    token_endpoint: SafeUrlSchema,\n    registration_endpoint: SafeUrlSchema.optional(),\n    scopes_supported: z.array(z.string()).optional(),\n    response_types_supported: z.array(z.string()),\n    response_modes_supported: z.array(z.string()).optional(),\n    grant_types_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    service_documentation: SafeUrlSchema.optional(),\n    revocation_endpoint: SafeUrlSchema.optional(),\n    revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    introspection_endpoint: z.string().optional(),\n    introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    code_challenge_methods_supported: z.array(z.string()).optional(),\n    client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n    issuer: z.string(),\n    authorization_endpoint: SafeUrlSchema,\n    token_endpoint: SafeUrlSchema,\n    userinfo_endpoint: SafeUrlSchema.optional(),\n    jwks_uri: SafeUrlSchema,\n    registration_endpoint: SafeUrlSchema.optional(),\n    scopes_supported: z.array(z.string()).optional(),\n    response_types_supported: z.array(z.string()),\n    response_modes_supported: z.array(z.string()).optional(),\n    grant_types_supported: z.array(z.string()).optional(),\n    acr_values_supported: z.array(z.string()).optional(),\n    subject_types_supported: z.array(z.string()),\n    id_token_signing_alg_values_supported: z.array(z.string()),\n    id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n    id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n    userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n    userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n    userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n    request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n    request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n    request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n    token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n    display_values_supported: z.array(z.string()).optional(),\n    claim_types_supported: z.array(z.string()).optional(),\n    claims_supported: z.array(z.string()).optional(),\n    service_documentation: z.string().optional(),\n    claims_locales_supported: z.array(z.string()).optional(),\n    ui_locales_supported: z.array(z.string()).optional(),\n    claims_parameter_supported: z.boolean().optional(),\n    request_parameter_supported: z.boolean().optional(),\n    request_uri_parameter_supported: z.boolean().optional(),\n    require_request_uri_registration: z.boolean().optional(),\n    op_policy_uri: SafeUrlSchema.optional(),\n    op_tos_uri: SafeUrlSchema.optional(),\n    client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n    ...OpenIdProviderMetadataSchema.shape,\n    ...OAuthMetadataSchema.pick({\n        code_challenge_methods_supported: true\n    }).shape\n});\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n    .object({\n    access_token: z.string(),\n    id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n    token_type: z.string(),\n    expires_in: z.coerce.number().optional(),\n    scope: z.string().optional(),\n    refresh_token: z.string().optional()\n})\n    .strip();\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n    error: z.string(),\n    error_description: z.string().optional(),\n    error_uri: z.string().optional()\n});\n/**\n * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri\n */\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n    .object({\n    redirect_uris: z.array(SafeUrlSchema),\n    token_endpoint_auth_method: z.string().optional(),\n    grant_types: z.array(z.string()).optional(),\n    response_types: z.array(z.string()).optional(),\n    client_name: z.string().optional(),\n    client_uri: SafeUrlSchema.optional(),\n    logo_uri: OptionalSafeUrlSchema,\n    scope: z.string().optional(),\n    contacts: z.array(z.string()).optional(),\n    tos_uri: OptionalSafeUrlSchema,\n    policy_uri: z.string().optional(),\n    jwks_uri: SafeUrlSchema.optional(),\n    jwks: z.any().optional(),\n    software_id: z.string().optional(),\n    software_version: z.string().optional(),\n    software_statement: z.string().optional()\n})\n    .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n    .object({\n    client_id: z.string(),\n    client_secret: z.string().optional(),\n    client_id_issued_at: z.number().optional(),\n    client_secret_expires_at: z.number().optional()\n})\n    .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n    .object({\n    error: z.string(),\n    error_description: z.string().optional()\n})\n    .strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n    .object({\n    token: z.string(),\n    token_type_hint: z.string().optional()\n})\n    .strip();\n//# sourceMappingURL=auth.js.map","/**\n * Base class for all OAuth errors\n */\nexport class OAuthError extends Error {\n    constructor(message, errorUri) {\n        super(message);\n        this.errorUri = errorUri;\n        this.name = this.constructor.name;\n    }\n    /**\n     * Converts the error to a standard OAuth error response object\n     */\n    toResponseObject() {\n        const response = {\n            error: this.errorCode,\n            error_description: this.message\n        };\n        if (this.errorUri) {\n            response.error_uri = this.errorUri;\n        }\n        return response;\n    }\n    get errorCode() {\n        return this.constructor.errorCode;\n    }\n}\n/**\n * Invalid request error - The request is missing a required parameter,\n * includes an invalid parameter value, includes a parameter more than once,\n * or is otherwise malformed.\n */\nexport class InvalidRequestError extends OAuthError {\n}\nInvalidRequestError.errorCode = 'invalid_request';\n/**\n * Invalid client error - Client authentication failed (e.g., unknown client, no client\n * authentication included, or unsupported authentication method).\n */\nexport class InvalidClientError extends OAuthError {\n}\nInvalidClientError.errorCode = 'invalid_client';\n/**\n * Invalid grant error - The provided authorization grant or refresh token is\n * invalid, expired, revoked, does not match the redirection URI used in the\n * authorization request, or was issued to another client.\n */\nexport class InvalidGrantError extends OAuthError {\n}\nInvalidGrantError.errorCode = 'invalid_grant';\n/**\n * Unauthorized client error - The authenticated client is not authorized to use\n * this authorization grant type.\n */\nexport class UnauthorizedClientError extends OAuthError {\n}\nUnauthorizedClientError.errorCode = 'unauthorized_client';\n/**\n * Unsupported grant type error - The authorization grant type is not supported\n * by the authorization server.\n */\nexport class UnsupportedGrantTypeError extends OAuthError {\n}\nUnsupportedGrantTypeError.errorCode = 'unsupported_grant_type';\n/**\n * Invalid scope error - The requested scope is invalid, unknown, malformed, or\n * exceeds the scope granted by the resource owner.\n */\nexport class InvalidScopeError extends OAuthError {\n}\nInvalidScopeError.errorCode = 'invalid_scope';\n/**\n * Access denied error - The resource owner or authorization server denied the request.\n */\nexport class AccessDeniedError extends OAuthError {\n}\nAccessDeniedError.errorCode = 'access_denied';\n/**\n * Server error - The authorization server encountered an unexpected condition\n * that prevented it from fulfilling the request.\n */\nexport class ServerError extends OAuthError {\n}\nServerError.errorCode = 'server_error';\n/**\n * Temporarily unavailable error - The authorization server is currently unable to\n * handle the request due to a temporary overloading or maintenance of the server.\n */\nexport class TemporarilyUnavailableError extends OAuthError {\n}\nTemporarilyUnavailableError.errorCode = 'temporarily_unavailable';\n/**\n * Unsupported response type error - The authorization server does not support\n * obtaining an authorization code using this method.\n */\nexport class UnsupportedResponseTypeError extends OAuthError {\n}\nUnsupportedResponseTypeError.errorCode = 'unsupported_response_type';\n/**\n * Unsupported token type error - The authorization server does not support\n * the requested token type.\n */\nexport class UnsupportedTokenTypeError extends OAuthError {\n}\nUnsupportedTokenTypeError.errorCode = 'unsupported_token_type';\n/**\n * Invalid token error - The access token provided is expired, revoked, malformed,\n * or invalid for other reasons.\n */\nexport class InvalidTokenError extends OAuthError {\n}\nInvalidTokenError.errorCode = 'invalid_token';\n/**\n * Method not allowed error - The HTTP method used is not allowed for this endpoint.\n * (Custom, non-standard error)\n */\nexport class MethodNotAllowedError extends OAuthError {\n}\nMethodNotAllowedError.errorCode = 'method_not_allowed';\n/**\n * Too many requests error - Rate limit exceeded.\n * (Custom, non-standard error based on RFC 6585)\n */\nexport class TooManyRequestsError extends OAuthError {\n}\nTooManyRequestsError.errorCode = 'too_many_requests';\n/**\n * Invalid client metadata error - The client metadata is invalid.\n * (Custom error for dynamic client registration - RFC 7591)\n */\nexport class InvalidClientMetadataError extends OAuthError {\n}\nInvalidClientMetadataError.errorCode = 'invalid_client_metadata';\n/**\n * Insufficient scope error - The request requires higher privileges than provided by the access token.\n */\nexport class InsufficientScopeError extends OAuthError {\n}\nInsufficientScopeError.errorCode = 'insufficient_scope';\n/**\n * Invalid target error - The requested resource is invalid, missing, unknown, or malformed.\n * (Custom error for resource indicators - RFC 8707)\n */\nexport class InvalidTargetError extends OAuthError {\n}\nInvalidTargetError.errorCode = 'invalid_target';\n/**\n * A utility class for defining one-off error codes\n */\nexport class CustomOAuthError extends OAuthError {\n    constructor(customErrorCode, message, errorUri) {\n        super(message, errorUri);\n        this.customErrorCode = customErrorCode;\n    }\n    get errorCode() {\n        return this.customErrorCode;\n    }\n}\n/**\n * A full list of all OAuthErrors, enabling parsing from error responses\n */\nexport const OAUTH_ERRORS = {\n    [InvalidRequestError.errorCode]: InvalidRequestError,\n    [InvalidClientError.errorCode]: InvalidClientError,\n    [InvalidGrantError.errorCode]: InvalidGrantError,\n    [UnauthorizedClientError.errorCode]: UnauthorizedClientError,\n    [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,\n    [InvalidScopeError.errorCode]: InvalidScopeError,\n    [AccessDeniedError.errorCode]: AccessDeniedError,\n    [ServerError.errorCode]: ServerError,\n    [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,\n    [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,\n    [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,\n    [InvalidTokenError.errorCode]: InvalidTokenError,\n    [MethodNotAllowedError.errorCode]: MethodNotAllowedError,\n    [TooManyRequestsError.errorCode]: TooManyRequestsError,\n    [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,\n    [InsufficientScopeError.errorCode]: InsufficientScopeError,\n    [InvalidTargetError.errorCode]: InvalidTargetError\n};\n//# sourceMappingURL=errors.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass _CodeOrName {\n}\nexports._CodeOrName = _CodeOrName;\nexports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;\nclass Name extends _CodeOrName {\n    constructor(s) {\n        super();\n        if (!exports.IDENTIFIER.test(s))\n            throw new Error(\"CodeGen: name must be a valid identifier\");\n        this.str = s;\n    }\n    toString() {\n        return this.str;\n    }\n    emptyStr() {\n        return false;\n    }\n    get names() {\n        return { [this.str]: 1 };\n    }\n}\nexports.Name = Name;\nclass _Code extends _CodeOrName {\n    constructor(code) {\n        super();\n        this._items = typeof code === \"string\" ? [code] : code;\n    }\n    toString() {\n        return this.str;\n    }\n    emptyStr() {\n        if (this._items.length > 1)\n            return false;\n        const item = this._items[0];\n        return item === \"\" || item === '\"\"';\n    }\n    get str() {\n        var _a;\n        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, \"\")));\n    }\n    get names() {\n        var _a;\n        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {\n            if (c instanceof Name)\n                names[c.str] = (names[c.str] || 0) + 1;\n            return names;\n        }, {})));\n    }\n}\nexports._Code = _Code;\nexports.nil = new _Code(\"\");\nfunction _(strs, ...args) {\n    const code = [strs[0]];\n    let i = 0;\n    while (i < args.length) {\n        addCodeArg(code, args[i]);\n        code.push(strs[++i]);\n    }\n    return new _Code(code);\n}\nexports._ = _;\nconst plus = new _Code(\"+\");\nfunction str(strs, ...args) {\n    const expr = [safeStringify(strs[0])];\n    let i = 0;\n    while (i < args.length) {\n        expr.push(plus);\n        addCodeArg(expr, args[i]);\n        expr.push(plus, safeStringify(strs[++i]));\n    }\n    optimize(expr);\n    return new _Code(expr);\n}\nexports.str = str;\nfunction addCodeArg(code, arg) {\n    if (arg instanceof _Code)\n        code.push(...arg._items);\n    else if (arg instanceof Name)\n        code.push(arg);\n    else\n        code.push(interpolate(arg));\n}\nexports.addCodeArg = addCodeArg;\nfunction optimize(expr) {\n    let i = 1;\n    while (i < expr.length - 1) {\n        if (expr[i] === plus) {\n            const res = mergeExprItems(expr[i - 1], expr[i + 1]);\n            if (res !== undefined) {\n                expr.splice(i - 1, 3, res);\n                continue;\n            }\n            expr[i++] = \"+\";\n        }\n        i++;\n    }\n}\nfunction mergeExprItems(a, b) {\n    if (b === '\"\"')\n        return a;\n    if (a === '\"\"')\n        return b;\n    if (typeof a == \"string\") {\n        if (b instanceof Name || a[a.length - 1] !== '\"')\n            return;\n        if (typeof b != \"string\")\n            return `${a.slice(0, -1)}${b}\"`;\n        if (b[0] === '\"')\n            return a.slice(0, -1) + b.slice(1);\n        return;\n    }\n    if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name))\n        return `\"${a}${b.slice(1)}`;\n    return;\n}\nfunction strConcat(c1, c2) {\n    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;\n}\nexports.strConcat = strConcat;\n// TODO do not allow arrays here\nfunction interpolate(x) {\n    return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n        ? x\n        : safeStringify(Array.isArray(x) ? x.join(\",\") : x);\n}\nfunction stringify(x) {\n    return new _Code(safeStringify(x));\n}\nexports.stringify = stringify;\nfunction safeStringify(x) {\n    return JSON.stringify(x)\n        .replace(/\\u2028/g, \"\\\\u2028\")\n        .replace(/\\u2029/g, \"\\\\u2029\");\n}\nexports.safeStringify = safeStringify;\nfunction getProperty(key) {\n    return typeof key == \"string\" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;\n}\nexports.getProperty = getProperty;\n//Does best effort to format the name properly\nfunction getEsmExportName(key) {\n    if (typeof key == \"string\" && exports.IDENTIFIER.test(key)) {\n        return new _Code(`${key}`);\n    }\n    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);\n}\nexports.getEsmExportName = getEsmExportName;\nfunction regexpCode(rx) {\n    return new _Code(rx.toString());\n}\nexports.regexpCode = regexpCode;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;\nconst code_1 = require(\"./code\");\nclass ValueError extends Error {\n    constructor(name) {\n        super(`CodeGen: \"code\" for ${name} not defined`);\n        this.value = name.value;\n    }\n}\nvar UsedValueState;\n(function (UsedValueState) {\n    UsedValueState[UsedValueState[\"Started\"] = 0] = \"Started\";\n    UsedValueState[UsedValueState[\"Completed\"] = 1] = \"Completed\";\n})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));\nexports.varKinds = {\n    const: new code_1.Name(\"const\"),\n    let: new code_1.Name(\"let\"),\n    var: new code_1.Name(\"var\"),\n};\nclass Scope {\n    constructor({ prefixes, parent } = {}) {\n        this._names = {};\n        this._prefixes = prefixes;\n        this._parent = parent;\n    }\n    toName(nameOrPrefix) {\n        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);\n    }\n    name(prefix) {\n        return new code_1.Name(this._newName(prefix));\n    }\n    _newName(prefix) {\n        const ng = this._names[prefix] || this._nameGroup(prefix);\n        return `${prefix}${ng.index++}`;\n    }\n    _nameGroup(prefix) {\n        var _a, _b;\n        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {\n            throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`);\n        }\n        return (this._names[prefix] = { prefix, index: 0 });\n    }\n}\nexports.Scope = Scope;\nclass ValueScopeName extends code_1.Name {\n    constructor(prefix, nameStr) {\n        super(nameStr);\n        this.prefix = prefix;\n    }\n    setValue(value, { property, itemIndex }) {\n        this.value = value;\n        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;\n    }\n}\nexports.ValueScopeName = ValueScopeName;\nconst line = (0, code_1._) `\\n`;\nclass ValueScope extends Scope {\n    constructor(opts) {\n        super(opts);\n        this._values = {};\n        this._scope = opts.scope;\n        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };\n    }\n    get() {\n        return this._scope;\n    }\n    name(prefix) {\n        return new ValueScopeName(prefix, this._newName(prefix));\n    }\n    value(nameOrPrefix, value) {\n        var _a;\n        if (value.ref === undefined)\n            throw new Error(\"CodeGen: ref must be passed in value\");\n        const name = this.toName(nameOrPrefix);\n        const { prefix } = name;\n        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;\n        let vs = this._values[prefix];\n        if (vs) {\n            const _name = vs.get(valueKey);\n            if (_name)\n                return _name;\n        }\n        else {\n            vs = this._values[prefix] = new Map();\n        }\n        vs.set(valueKey, name);\n        const s = this._scope[prefix] || (this._scope[prefix] = []);\n        const itemIndex = s.length;\n        s[itemIndex] = value.ref;\n        name.setValue(value, { property: prefix, itemIndex });\n        return name;\n    }\n    getValue(prefix, keyOrRef) {\n        const vs = this._values[prefix];\n        if (!vs)\n            return;\n        return vs.get(keyOrRef);\n    }\n    scopeRefs(scopeName, values = this._values) {\n        return this._reduceValues(values, (name) => {\n            if (name.scopePath === undefined)\n                throw new Error(`CodeGen: name \"${name}\" has no value`);\n            return (0, code_1._) `${scopeName}${name.scopePath}`;\n        });\n    }\n    scopeCode(values = this._values, usedValues, getCode) {\n        return this._reduceValues(values, (name) => {\n            if (name.value === undefined)\n                throw new Error(`CodeGen: name \"${name}\" has no value`);\n            return name.value.code;\n        }, usedValues, getCode);\n    }\n    _reduceValues(values, valueCode, usedValues = {}, getCode) {\n        let code = code_1.nil;\n        for (const prefix in values) {\n            const vs = values[prefix];\n            if (!vs)\n                continue;\n            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());\n            vs.forEach((name) => {\n                if (nameSet.has(name))\n                    return;\n                nameSet.set(name, UsedValueState.Started);\n                let c = valueCode(name);\n                if (c) {\n                    const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;\n                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;\n                }\n                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {\n                    code = (0, code_1._) `${code}${c}${this.opts._n}`;\n                }\n                else {\n                    throw new ValueError(name);\n                }\n                nameSet.set(name, UsedValueState.Completed);\n            });\n        }\n        return code;\n    }\n}\nexports.ValueScope = ValueScope;\n//# sourceMappingURL=scope.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;\nconst code_1 = require(\"./code\");\nconst scope_1 = require(\"./scope\");\nvar code_2 = require(\"./code\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return code_2._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return code_2.str; } });\nObject.defineProperty(exports, \"strConcat\", { enumerable: true, get: function () { return code_2.strConcat; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return code_2.nil; } });\nObject.defineProperty(exports, \"getProperty\", { enumerable: true, get: function () { return code_2.getProperty; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return code_2.stringify; } });\nObject.defineProperty(exports, \"regexpCode\", { enumerable: true, get: function () { return code_2.regexpCode; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return code_2.Name; } });\nvar scope_2 = require(\"./scope\");\nObject.defineProperty(exports, \"Scope\", { enumerable: true, get: function () { return scope_2.Scope; } });\nObject.defineProperty(exports, \"ValueScope\", { enumerable: true, get: function () { return scope_2.ValueScope; } });\nObject.defineProperty(exports, \"ValueScopeName\", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });\nObject.defineProperty(exports, \"varKinds\", { enumerable: true, get: function () { return scope_2.varKinds; } });\nexports.operators = {\n    GT: new code_1._Code(\">\"),\n    GTE: new code_1._Code(\">=\"),\n    LT: new code_1._Code(\"<\"),\n    LTE: new code_1._Code(\"<=\"),\n    EQ: new code_1._Code(\"===\"),\n    NEQ: new code_1._Code(\"!==\"),\n    NOT: new code_1._Code(\"!\"),\n    OR: new code_1._Code(\"||\"),\n    AND: new code_1._Code(\"&&\"),\n    ADD: new code_1._Code(\"+\"),\n};\nclass Node {\n    optimizeNodes() {\n        return this;\n    }\n    optimizeNames(_names, _constants) {\n        return this;\n    }\n}\nclass Def extends Node {\n    constructor(varKind, name, rhs) {\n        super();\n        this.varKind = varKind;\n        this.name = name;\n        this.rhs = rhs;\n    }\n    render({ es5, _n }) {\n        const varKind = es5 ? scope_1.varKinds.var : this.varKind;\n        const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`;\n        return `${varKind} ${this.name}${rhs};` + _n;\n    }\n    optimizeNames(names, constants) {\n        if (!names[this.name.str])\n            return;\n        if (this.rhs)\n            this.rhs = optimizeExpr(this.rhs, names, constants);\n        return this;\n    }\n    get names() {\n        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};\n    }\n}\nclass Assign extends Node {\n    constructor(lhs, rhs, sideEffects) {\n        super();\n        this.lhs = lhs;\n        this.rhs = rhs;\n        this.sideEffects = sideEffects;\n    }\n    render({ _n }) {\n        return `${this.lhs} = ${this.rhs};` + _n;\n    }\n    optimizeNames(names, constants) {\n        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)\n            return;\n        this.rhs = optimizeExpr(this.rhs, names, constants);\n        return this;\n    }\n    get names() {\n        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };\n        return addExprNames(names, this.rhs);\n    }\n}\nclass AssignOp extends Assign {\n    constructor(lhs, op, rhs, sideEffects) {\n        super(lhs, rhs, sideEffects);\n        this.op = op;\n    }\n    render({ _n }) {\n        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;\n    }\n}\nclass Label extends Node {\n    constructor(label) {\n        super();\n        this.label = label;\n        this.names = {};\n    }\n    render({ _n }) {\n        return `${this.label}:` + _n;\n    }\n}\nclass Break extends Node {\n    constructor(label) {\n        super();\n        this.label = label;\n        this.names = {};\n    }\n    render({ _n }) {\n        const label = this.label ? ` ${this.label}` : \"\";\n        return `break${label};` + _n;\n    }\n}\nclass Throw extends Node {\n    constructor(error) {\n        super();\n        this.error = error;\n    }\n    render({ _n }) {\n        return `throw ${this.error};` + _n;\n    }\n    get names() {\n        return this.error.names;\n    }\n}\nclass AnyCode extends Node {\n    constructor(code) {\n        super();\n        this.code = code;\n    }\n    render({ _n }) {\n        return `${this.code};` + _n;\n    }\n    optimizeNodes() {\n        return `${this.code}` ? this : undefined;\n    }\n    optimizeNames(names, constants) {\n        this.code = optimizeExpr(this.code, names, constants);\n        return this;\n    }\n    get names() {\n        return this.code instanceof code_1._CodeOrName ? this.code.names : {};\n    }\n}\nclass ParentNode extends Node {\n    constructor(nodes = []) {\n        super();\n        this.nodes = nodes;\n    }\n    render(opts) {\n        return this.nodes.reduce((code, n) => code + n.render(opts), \"\");\n    }\n    optimizeNodes() {\n        const { nodes } = this;\n        let i = nodes.length;\n        while (i--) {\n            const n = nodes[i].optimizeNodes();\n            if (Array.isArray(n))\n                nodes.splice(i, 1, ...n);\n            else if (n)\n                nodes[i] = n;\n            else\n                nodes.splice(i, 1);\n        }\n        return nodes.length > 0 ? this : undefined;\n    }\n    optimizeNames(names, constants) {\n        const { nodes } = this;\n        let i = nodes.length;\n        while (i--) {\n            // iterating backwards improves 1-pass optimization\n            const n = nodes[i];\n            if (n.optimizeNames(names, constants))\n                continue;\n            subtractNames(names, n.names);\n            nodes.splice(i, 1);\n        }\n        return nodes.length > 0 ? this : undefined;\n    }\n    get names() {\n        return this.nodes.reduce((names, n) => addNames(names, n.names), {});\n    }\n}\nclass BlockNode extends ParentNode {\n    render(opts) {\n        return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n;\n    }\n}\nclass Root extends ParentNode {\n}\nclass Else extends BlockNode {\n}\nElse.kind = \"else\";\nclass If extends BlockNode {\n    constructor(condition, nodes) {\n        super(nodes);\n        this.condition = condition;\n    }\n    render(opts) {\n        let code = `if(${this.condition})` + super.render(opts);\n        if (this.else)\n            code += \"else \" + this.else.render(opts);\n        return code;\n    }\n    optimizeNodes() {\n        super.optimizeNodes();\n        const cond = this.condition;\n        if (cond === true)\n            return this.nodes; // else is ignored here\n        let e = this.else;\n        if (e) {\n            const ns = e.optimizeNodes();\n            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;\n        }\n        if (e) {\n            if (cond === false)\n                return e instanceof If ? e : e.nodes;\n            if (this.nodes.length)\n                return this;\n            return new If(not(cond), e instanceof If ? [e] : e.nodes);\n        }\n        if (cond === false || !this.nodes.length)\n            return undefined;\n        return this;\n    }\n    optimizeNames(names, constants) {\n        var _a;\n        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n        if (!(super.optimizeNames(names, constants) || this.else))\n            return;\n        this.condition = optimizeExpr(this.condition, names, constants);\n        return this;\n    }\n    get names() {\n        const names = super.names;\n        addExprNames(names, this.condition);\n        if (this.else)\n            addNames(names, this.else.names);\n        return names;\n    }\n}\nIf.kind = \"if\";\nclass For extends BlockNode {\n}\nFor.kind = \"for\";\nclass ForLoop extends For {\n    constructor(iteration) {\n        super();\n        this.iteration = iteration;\n    }\n    render(opts) {\n        return `for(${this.iteration})` + super.render(opts);\n    }\n    optimizeNames(names, constants) {\n        if (!super.optimizeNames(names, constants))\n            return;\n        this.iteration = optimizeExpr(this.iteration, names, constants);\n        return this;\n    }\n    get names() {\n        return addNames(super.names, this.iteration.names);\n    }\n}\nclass ForRange extends For {\n    constructor(varKind, name, from, to) {\n        super();\n        this.varKind = varKind;\n        this.name = name;\n        this.from = from;\n        this.to = to;\n    }\n    render(opts) {\n        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;\n        const { name, from, to } = this;\n        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);\n    }\n    get names() {\n        const names = addExprNames(super.names, this.from);\n        return addExprNames(names, this.to);\n    }\n}\nclass ForIter extends For {\n    constructor(loop, varKind, name, iterable) {\n        super();\n        this.loop = loop;\n        this.varKind = varKind;\n        this.name = name;\n        this.iterable = iterable;\n    }\n    render(opts) {\n        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);\n    }\n    optimizeNames(names, constants) {\n        if (!super.optimizeNames(names, constants))\n            return;\n        this.iterable = optimizeExpr(this.iterable, names, constants);\n        return this;\n    }\n    get names() {\n        return addNames(super.names, this.iterable.names);\n    }\n}\nclass Func extends BlockNode {\n    constructor(name, args, async) {\n        super();\n        this.name = name;\n        this.args = args;\n        this.async = async;\n    }\n    render(opts) {\n        const _async = this.async ? \"async \" : \"\";\n        return `${_async}function ${this.name}(${this.args})` + super.render(opts);\n    }\n}\nFunc.kind = \"func\";\nclass Return extends ParentNode {\n    render(opts) {\n        return \"return \" + super.render(opts);\n    }\n}\nReturn.kind = \"return\";\nclass Try extends BlockNode {\n    render(opts) {\n        let code = \"try\" + super.render(opts);\n        if (this.catch)\n            code += this.catch.render(opts);\n        if (this.finally)\n            code += this.finally.render(opts);\n        return code;\n    }\n    optimizeNodes() {\n        var _a, _b;\n        super.optimizeNodes();\n        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();\n        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();\n        return this;\n    }\n    optimizeNames(names, constants) {\n        var _a, _b;\n        super.optimizeNames(names, constants);\n        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);\n        return this;\n    }\n    get names() {\n        const names = super.names;\n        if (this.catch)\n            addNames(names, this.catch.names);\n        if (this.finally)\n            addNames(names, this.finally.names);\n        return names;\n    }\n}\nclass Catch extends BlockNode {\n    constructor(error) {\n        super();\n        this.error = error;\n    }\n    render(opts) {\n        return `catch(${this.error})` + super.render(opts);\n    }\n}\nCatch.kind = \"catch\";\nclass Finally extends BlockNode {\n    render(opts) {\n        return \"finally\" + super.render(opts);\n    }\n}\nFinally.kind = \"finally\";\nclass CodeGen {\n    constructor(extScope, opts = {}) {\n        this._values = {};\n        this._blockStarts = [];\n        this._constants = {};\n        this.opts = { ...opts, _n: opts.lines ? \"\\n\" : \"\" };\n        this._extScope = extScope;\n        this._scope = new scope_1.Scope({ parent: extScope });\n        this._nodes = [new Root()];\n    }\n    toString() {\n        return this._root.render(this.opts);\n    }\n    // returns unique name in the internal scope\n    name(prefix) {\n        return this._scope.name(prefix);\n    }\n    // reserves unique name in the external scope\n    scopeName(prefix) {\n        return this._extScope.name(prefix);\n    }\n    // reserves unique name in the external scope and assigns value to it\n    scopeValue(prefixOrName, value) {\n        const name = this._extScope.value(prefixOrName, value);\n        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());\n        vs.add(name);\n        return name;\n    }\n    getScopeValue(prefix, keyOrRef) {\n        return this._extScope.getValue(prefix, keyOrRef);\n    }\n    // return code that assigns values in the external scope to the names that are used internally\n    // (same names that were returned by gen.scopeName or gen.scopeValue)\n    scopeRefs(scopeName) {\n        return this._extScope.scopeRefs(scopeName, this._values);\n    }\n    scopeCode() {\n        return this._extScope.scopeCode(this._values);\n    }\n    _def(varKind, nameOrPrefix, rhs, constant) {\n        const name = this._scope.toName(nameOrPrefix);\n        if (rhs !== undefined && constant)\n            this._constants[name.str] = rhs;\n        this._leafNode(new Def(varKind, name, rhs));\n        return name;\n    }\n    // `const` declaration (`var` in es5 mode)\n    const(nameOrPrefix, rhs, _constant) {\n        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);\n    }\n    // `let` declaration with optional assignment (`var` in es5 mode)\n    let(nameOrPrefix, rhs, _constant) {\n        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);\n    }\n    // `var` declaration with optional assignment\n    var(nameOrPrefix, rhs, _constant) {\n        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);\n    }\n    // assignment code\n    assign(lhs, rhs, sideEffects) {\n        return this._leafNode(new Assign(lhs, rhs, sideEffects));\n    }\n    // `+=` code\n    add(lhs, rhs) {\n        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));\n    }\n    // appends passed SafeExpr to code or executes Block\n    code(c) {\n        if (typeof c == \"function\")\n            c();\n        else if (c !== code_1.nil)\n            this._leafNode(new AnyCode(c));\n        return this;\n    }\n    // returns code for object literal for the passed argument list of key-value pairs\n    object(...keyValues) {\n        const code = [\"{\"];\n        for (const [key, value] of keyValues) {\n            if (code.length > 1)\n                code.push(\",\");\n            code.push(key);\n            if (key !== value || this.opts.es5) {\n                code.push(\":\");\n                (0, code_1.addCodeArg)(code, value);\n            }\n        }\n        code.push(\"}\");\n        return new code_1._Code(code);\n    }\n    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n    if(condition, thenBody, elseBody) {\n        this._blockNode(new If(condition));\n        if (thenBody && elseBody) {\n            this.code(thenBody).else().code(elseBody).endIf();\n        }\n        else if (thenBody) {\n            this.code(thenBody).endIf();\n        }\n        else if (elseBody) {\n            throw new Error('CodeGen: \"else\" body without \"then\" body');\n        }\n        return this;\n    }\n    // `else if` clause - invalid without `if` or after `else` clauses\n    elseIf(condition) {\n        return this._elseNode(new If(condition));\n    }\n    // `else` clause - only valid after `if` or `else if` clauses\n    else() {\n        return this._elseNode(new Else());\n    }\n    // end `if` statement (needed if gen.if was used only with condition)\n    endIf() {\n        return this._endBlockNode(If, Else);\n    }\n    _for(node, forBody) {\n        this._blockNode(node);\n        if (forBody)\n            this.code(forBody).endFor();\n        return this;\n    }\n    // a generic `for` clause (or statement if `forBody` is passed)\n    for(iteration, forBody) {\n        return this._for(new ForLoop(iteration), forBody);\n    }\n    // `for` statement for a range of values\n    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {\n        const name = this._scope.toName(nameOrPrefix);\n        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));\n    }\n    // `for-of` statement (in es5 mode replace with a normal for loop)\n    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {\n        const name = this._scope.toName(nameOrPrefix);\n        if (this.opts.es5) {\n            const arr = iterable instanceof code_1.Name ? iterable : this.var(\"_arr\", iterable);\n            return this.forRange(\"_i\", 0, (0, code_1._) `${arr}.length`, (i) => {\n                this.var(name, (0, code_1._) `${arr}[${i}]`);\n                forBody(name);\n            });\n        }\n        return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name));\n    }\n    // `for-in` statement.\n    // With option `ownProperties` replaced with a `for-of` loop for object keys\n    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {\n        if (this.opts.ownProperties) {\n            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);\n        }\n        const name = this._scope.toName(nameOrPrefix);\n        return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name));\n    }\n    // end `for` loop\n    endFor() {\n        return this._endBlockNode(For);\n    }\n    // `label` statement\n    label(label) {\n        return this._leafNode(new Label(label));\n    }\n    // `break` statement\n    break(label) {\n        return this._leafNode(new Break(label));\n    }\n    // `return` statement\n    return(value) {\n        const node = new Return();\n        this._blockNode(node);\n        this.code(value);\n        if (node.nodes.length !== 1)\n            throw new Error('CodeGen: \"return\" should have one node');\n        return this._endBlockNode(Return);\n    }\n    // `try` statement\n    try(tryBody, catchCode, finallyCode) {\n        if (!catchCode && !finallyCode)\n            throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"');\n        const node = new Try();\n        this._blockNode(node);\n        this.code(tryBody);\n        if (catchCode) {\n            const error = this.name(\"e\");\n            this._currNode = node.catch = new Catch(error);\n            catchCode(error);\n        }\n        if (finallyCode) {\n            this._currNode = node.finally = new Finally();\n            this.code(finallyCode);\n        }\n        return this._endBlockNode(Catch, Finally);\n    }\n    // `throw` statement\n    throw(error) {\n        return this._leafNode(new Throw(error));\n    }\n    // start self-balancing block\n    block(body, nodeCount) {\n        this._blockStarts.push(this._nodes.length);\n        if (body)\n            this.code(body).endBlock(nodeCount);\n        return this;\n    }\n    // end the current self-balancing block\n    endBlock(nodeCount) {\n        const len = this._blockStarts.pop();\n        if (len === undefined)\n            throw new Error(\"CodeGen: not in self-balancing block\");\n        const toClose = this._nodes.length - len;\n        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);\n        }\n        this._nodes.length = len;\n        return this;\n    }\n    // `function` heading (or definition if funcBody is passed)\n    func(name, args = code_1.nil, async, funcBody) {\n        this._blockNode(new Func(name, args, async));\n        if (funcBody)\n            this.code(funcBody).endFunc();\n        return this;\n    }\n    // end function definition\n    endFunc() {\n        return this._endBlockNode(Func);\n    }\n    optimize(n = 1) {\n        while (n-- > 0) {\n            this._root.optimizeNodes();\n            this._root.optimizeNames(this._root.names, this._constants);\n        }\n    }\n    _leafNode(node) {\n        this._currNode.nodes.push(node);\n        return this;\n    }\n    _blockNode(node) {\n        this._currNode.nodes.push(node);\n        this._nodes.push(node);\n    }\n    _endBlockNode(N1, N2) {\n        const n = this._currNode;\n        if (n instanceof N1 || (N2 && n instanceof N2)) {\n            this._nodes.pop();\n            return this;\n        }\n        throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`);\n    }\n    _elseNode(node) {\n        const n = this._currNode;\n        if (!(n instanceof If)) {\n            throw new Error('CodeGen: \"else\" without \"if\"');\n        }\n        this._currNode = n.else = node;\n        return this;\n    }\n    get _root() {\n        return this._nodes[0];\n    }\n    get _currNode() {\n        const ns = this._nodes;\n        return ns[ns.length - 1];\n    }\n    set _currNode(node) {\n        const ns = this._nodes;\n        ns[ns.length - 1] = node;\n    }\n}\nexports.CodeGen = CodeGen;\nfunction addNames(names, from) {\n    for (const n in from)\n        names[n] = (names[n] || 0) + (from[n] || 0);\n    return names;\n}\nfunction addExprNames(names, from) {\n    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;\n}\nfunction optimizeExpr(expr, names, constants) {\n    if (expr instanceof code_1.Name)\n        return replaceName(expr);\n    if (!canOptimize(expr))\n        return expr;\n    return new code_1._Code(expr._items.reduce((items, c) => {\n        if (c instanceof code_1.Name)\n            c = replaceName(c);\n        if (c instanceof code_1._Code)\n            items.push(...c._items);\n        else\n            items.push(c);\n        return items;\n    }, []));\n    function replaceName(n) {\n        const c = constants[n.str];\n        if (c === undefined || names[n.str] !== 1)\n            return n;\n        delete names[n.str];\n        return c;\n    }\n    function canOptimize(e) {\n        return (e instanceof code_1._Code &&\n            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));\n    }\n}\nfunction subtractNames(names, from) {\n    for (const n in from)\n        names[n] = (names[n] || 0) - (from[n] || 0);\n}\nfunction not(x) {\n    return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : (0, code_1._) `!${par(x)}`;\n}\nexports.not = not;\nconst andCode = mappend(exports.operators.AND);\n// boolean AND (&&) expression with the passed arguments\nfunction and(...args) {\n    return args.reduce(andCode);\n}\nexports.and = and;\nconst orCode = mappend(exports.operators.OR);\n// boolean OR (||) expression with the passed arguments\nfunction or(...args) {\n    return args.reduce(orCode);\n}\nexports.or = or;\nfunction mappend(op) {\n    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);\n}\nfunction par(x) {\n    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst code_1 = require(\"./codegen/code\");\n// TODO refactor to use Set\nfunction toHash(arr) {\n    const hash = {};\n    for (const item of arr)\n        hash[item] = true;\n    return hash;\n}\nexports.toHash = toHash;\nfunction alwaysValidSchema(it, schema) {\n    if (typeof schema == \"boolean\")\n        return schema;\n    if (Object.keys(schema).length === 0)\n        return true;\n    checkUnknownRules(it, schema);\n    return !schemaHasRules(schema, it.self.RULES.all);\n}\nexports.alwaysValidSchema = alwaysValidSchema;\nfunction checkUnknownRules(it, schema = it.schema) {\n    const { opts, self } = it;\n    if (!opts.strictSchema)\n        return;\n    if (typeof schema === \"boolean\")\n        return;\n    const rules = self.RULES.keywords;\n    for (const key in schema) {\n        if (!rules[key])\n            checkStrictMode(it, `unknown keyword: \"${key}\"`);\n    }\n}\nexports.checkUnknownRules = checkUnknownRules;\nfunction schemaHasRules(schema, rules) {\n    if (typeof schema == \"boolean\")\n        return !schema;\n    for (const key in schema)\n        if (rules[key])\n            return true;\n    return false;\n}\nexports.schemaHasRules = schemaHasRules;\nfunction schemaHasRulesButRef(schema, RULES) {\n    if (typeof schema == \"boolean\")\n        return !schema;\n    for (const key in schema)\n        if (key !== \"$ref\" && RULES.all[key])\n            return true;\n    return false;\n}\nexports.schemaHasRulesButRef = schemaHasRulesButRef;\nfunction schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {\n    if (!$data) {\n        if (typeof schema == \"number\" || typeof schema == \"boolean\")\n            return schema;\n        if (typeof schema == \"string\")\n            return (0, codegen_1._) `${schema}`;\n    }\n    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;\n}\nexports.schemaRefOrVal = schemaRefOrVal;\nfunction unescapeFragment(str) {\n    return unescapeJsonPointer(decodeURIComponent(str));\n}\nexports.unescapeFragment = unescapeFragment;\nfunction escapeFragment(str) {\n    return encodeURIComponent(escapeJsonPointer(str));\n}\nexports.escapeFragment = escapeFragment;\nfunction escapeJsonPointer(str) {\n    if (typeof str == \"number\")\n        return `${str}`;\n    return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexports.escapeJsonPointer = escapeJsonPointer;\nfunction unescapeJsonPointer(str) {\n    return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\nexports.unescapeJsonPointer = unescapeJsonPointer;\nfunction eachItem(xs, f) {\n    if (Array.isArray(xs)) {\n        for (const x of xs)\n            f(x);\n    }\n    else {\n        f(xs);\n    }\n}\nexports.eachItem = eachItem;\nfunction makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {\n    return (gen, from, to, toName) => {\n        const res = to === undefined\n            ? from\n            : to instanceof codegen_1.Name\n                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n                : from instanceof codegen_1.Name\n                    ? (mergeToName(gen, to, from), from)\n                    : mergeValues(from, to);\n        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;\n    };\n}\nexports.mergeEvaluated = {\n    props: makeMergeEvaluated({\n        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {\n            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));\n        }),\n        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {\n            if (from === true) {\n                gen.assign(to, true);\n            }\n            else {\n                gen.assign(to, (0, codegen_1._) `${to} || {}`);\n                setEvaluated(gen, to, from);\n            }\n        }),\n        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),\n        resultToName: evaluatedPropsToName,\n    }),\n    items: makeMergeEvaluated({\n        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),\n        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),\n        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n        resultToName: (gen, items) => gen.var(\"items\", items),\n    }),\n};\nfunction evaluatedPropsToName(gen, ps) {\n    if (ps === true)\n        return gen.var(\"props\", true);\n    const props = gen.var(\"props\", (0, codegen_1._) `{}`);\n    if (ps !== undefined)\n        setEvaluated(gen, props, ps);\n    return props;\n}\nexports.evaluatedPropsToName = evaluatedPropsToName;\nfunction setEvaluated(gen, props, ps) {\n    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));\n}\nexports.setEvaluated = setEvaluated;\nconst snippets = {};\nfunction useFunc(gen, f) {\n    return gen.scopeValue(\"func\", {\n        ref: f,\n        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),\n    });\n}\nexports.useFunc = useFunc;\nvar Type;\n(function (Type) {\n    Type[Type[\"Num\"] = 0] = \"Num\";\n    Type[Type[\"Str\"] = 1] = \"Str\";\n})(Type || (exports.Type = Type = {}));\nfunction getErrorPath(dataProp, dataPropType, jsPropertySyntax) {\n    // let path\n    if (dataProp instanceof codegen_1.Name) {\n        const isNumber = dataPropType === Type.Num;\n        return jsPropertySyntax\n            ? isNumber\n                ? (0, codegen_1._) `\"[\" + ${dataProp} + \"]\"`\n                : (0, codegen_1._) `\"['\" + ${dataProp} + \"']\"`\n            : isNumber\n                ? (0, codegen_1._) `\"/\" + ${dataProp}`\n                : (0, codegen_1._) `\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")`; // TODO maybe use global escapePointer\n    }\n    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp);\n}\nexports.getErrorPath = getErrorPath;\nfunction checkStrictMode(it, msg, mode = it.opts.strictSchema) {\n    if (!mode)\n        return;\n    msg = `strict mode: ${msg}`;\n    if (mode === true)\n        throw new Error(msg);\n    it.self.logger.warn(msg);\n}\nexports.checkStrictMode = checkStrictMode;\n//# sourceMappingURL=util.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"./codegen\");\nconst names = {\n    // validation function arguments\n    data: new codegen_1.Name(\"data\"), // data passed to validation function\n    // args passed from referencing schema\n    valCxt: new codegen_1.Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n    instancePath: new codegen_1.Name(\"instancePath\"),\n    parentData: new codegen_1.Name(\"parentData\"),\n    parentDataProperty: new codegen_1.Name(\"parentDataProperty\"),\n    rootData: new codegen_1.Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n    dynamicAnchors: new codegen_1.Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n    // function scoped variables\n    vErrors: new codegen_1.Name(\"vErrors\"), // null or array of validation errors\n    errors: new codegen_1.Name(\"errors\"), // counter of validation errors\n    this: new codegen_1.Name(\"this\"),\n    // \"globals\"\n    self: new codegen_1.Name(\"self\"),\n    scope: new codegen_1.Name(\"scope\"),\n    // JTD serialize/parse name for JSON string and position\n    json: new codegen_1.Name(\"json\"),\n    jsonPos: new codegen_1.Name(\"jsonPos\"),\n    jsonLen: new codegen_1.Name(\"jsonLen\"),\n    jsonPart: new codegen_1.Name(\"jsonPart\"),\n};\nexports.default = names;\n//# sourceMappingURL=names.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst util_1 = require(\"./util\");\nconst names_1 = require(\"./names\");\nexports.keywordError = {\n    message: ({ keyword }) => (0, codegen_1.str) `must pass \"${keyword}\" keyword validation`,\n};\nexports.keyword$DataError = {\n    message: ({ keyword, schemaType }) => schemaType\n        ? (0, codegen_1.str) `\"${keyword}\" keyword must be ${schemaType} ($data)`\n        : (0, codegen_1.str) `\"${keyword}\" keyword is invalid ($data)`,\n};\nfunction reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {\n    const { it } = cxt;\n    const { gen, compositeRule, allErrors } = it;\n    const errObj = errorObjectCode(cxt, error, errorPaths);\n    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {\n        addError(gen, errObj);\n    }\n    else {\n        returnErrors(it, (0, codegen_1._) `[${errObj}]`);\n    }\n}\nexports.reportError = reportError;\nfunction reportExtraError(cxt, error = exports.keywordError, errorPaths) {\n    const { it } = cxt;\n    const { gen, compositeRule, allErrors } = it;\n    const errObj = errorObjectCode(cxt, error, errorPaths);\n    addError(gen, errObj);\n    if (!(compositeRule || allErrors)) {\n        returnErrors(it, names_1.default.vErrors);\n    }\n}\nexports.reportExtraError = reportExtraError;\nfunction resetErrorsCount(gen, errsCount) {\n    gen.assign(names_1.default.errors, errsCount);\n    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));\n}\nexports.resetErrorsCount = resetErrorsCount;\nfunction extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {\n    /* istanbul ignore if */\n    if (errsCount === undefined)\n        throw new Error(\"ajv implementation error\");\n    const err = gen.name(\"err\");\n    gen.forRange(\"i\", errsCount, names_1.default.errors, (i) => {\n        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);\n        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));\n        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);\n        if (it.opts.verbose) {\n            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);\n            gen.assign((0, codegen_1._) `${err}.data`, data);\n        }\n    });\n}\nexports.extendErrors = extendErrors;\nfunction addError(gen, errObj) {\n    const err = gen.const(\"err\", errObj);\n    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);\n    gen.code((0, codegen_1._) `${names_1.default.errors}++`);\n}\nfunction returnErrors(it, errs) {\n    const { gen, validateName, schemaEnv } = it;\n    if (schemaEnv.$async) {\n        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);\n    }\n    else {\n        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);\n        gen.return(false);\n    }\n}\nconst E = {\n    keyword: new codegen_1.Name(\"keyword\"),\n    schemaPath: new codegen_1.Name(\"schemaPath\"), // also used in JTD errors\n    params: new codegen_1.Name(\"params\"),\n    propertyName: new codegen_1.Name(\"propertyName\"),\n    message: new codegen_1.Name(\"message\"),\n    schema: new codegen_1.Name(\"schema\"),\n    parentSchema: new codegen_1.Name(\"parentSchema\"),\n};\nfunction errorObjectCode(cxt, error, errorPaths) {\n    const { createErrors } = cxt.it;\n    if (createErrors === false)\n        return (0, codegen_1._) `{}`;\n    return errorObject(cxt, error, errorPaths);\n}\nfunction errorObject(cxt, error, errorPaths = {}) {\n    const { gen, it } = cxt;\n    const keyValues = [\n        errorInstancePath(it, errorPaths),\n        errorSchemaPath(cxt, errorPaths),\n    ];\n    extraErrorProps(cxt, error, keyValues);\n    return gen.object(...keyValues);\n}\nfunction errorInstancePath({ errorPath }, { instancePath }) {\n    const instPath = instancePath\n        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`\n        : errorPath;\n    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];\n}\nfunction errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {\n    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;\n    if (schemaPath) {\n        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;\n    }\n    return [E.schemaPath, schPath];\n}\nfunction extraErrorProps(cxt, { params, message }, keyValues) {\n    const { keyword, data, schemaValue, it } = cxt;\n    const { opts, propertyName, topSchemaRef, schemaPath } = it;\n    keyValues.push([E.keyword, keyword], [E.params, typeof params == \"function\" ? params(cxt) : params || (0, codegen_1._) `{}`]);\n    if (opts.messages) {\n        keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message]);\n    }\n    if (opts.verbose) {\n        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);\n    }\n    if (propertyName)\n        keyValues.push([E.propertyName, propertyName]);\n}\n//# sourceMappingURL=errors.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst boolError = {\n    message: \"boolean schema is false\",\n};\nfunction topBoolOrEmptySchema(it) {\n    const { gen, schema, validateName } = it;\n    if (schema === false) {\n        falseSchemaError(it, false);\n    }\n    else if (typeof schema == \"object\" && schema.$async === true) {\n        gen.return(names_1.default.data);\n    }\n    else {\n        gen.assign((0, codegen_1._) `${validateName}.errors`, null);\n        gen.return(true);\n    }\n}\nexports.topBoolOrEmptySchema = topBoolOrEmptySchema;\nfunction boolOrEmptySchema(it, valid) {\n    const { gen, schema } = it;\n    if (schema === false) {\n        gen.var(valid, false); // TODO var\n        falseSchemaError(it);\n    }\n    else {\n        gen.var(valid, true); // TODO var\n    }\n}\nexports.boolOrEmptySchema = boolOrEmptySchema;\nfunction falseSchemaError(it, overrideAllErrors) {\n    const { gen, data } = it;\n    // TODO maybe some other interface should be used for non-keyword validation errors...\n    const cxt = {\n        gen,\n        keyword: \"false schema\",\n        data,\n        schema: false,\n        schemaCode: false,\n        schemaValue: false,\n        params: {},\n        it,\n    };\n    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);\n}\n//# sourceMappingURL=boolSchema.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getRules = exports.isJSONType = void 0;\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"];\nconst jsonTypes = new Set(_jsonTypes);\nfunction isJSONType(x) {\n    return typeof x == \"string\" && jsonTypes.has(x);\n}\nexports.isJSONType = isJSONType;\nfunction getRules() {\n    const groups = {\n        number: { type: \"number\", rules: [] },\n        string: { type: \"string\", rules: [] },\n        array: { type: \"array\", rules: [] },\n        object: { type: \"object\", rules: [] },\n    };\n    return {\n        types: { ...groups, integer: true, boolean: true, null: true },\n        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],\n        post: { rules: [] },\n        all: {},\n        keywords: {},\n    };\n}\nexports.getRules = getRules;\n//# sourceMappingURL=rules.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;\nfunction schemaHasRulesForType({ schema, self }, type) {\n    const group = self.RULES.types[type];\n    return group && group !== true && shouldUseGroup(schema, group);\n}\nexports.schemaHasRulesForType = schemaHasRulesForType;\nfunction shouldUseGroup(schema, group) {\n    return group.rules.some((rule) => shouldUseRule(schema, rule));\n}\nexports.shouldUseGroup = shouldUseGroup;\nfunction shouldUseRule(schema, rule) {\n    var _a;\n    return (schema[rule.keyword] !== undefined ||\n        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));\n}\nexports.shouldUseRule = shouldUseRule;\n//# sourceMappingURL=applicability.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;\nconst rules_1 = require(\"../rules\");\nconst applicability_1 = require(\"./applicability\");\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nvar DataType;\n(function (DataType) {\n    DataType[DataType[\"Correct\"] = 0] = \"Correct\";\n    DataType[DataType[\"Wrong\"] = 1] = \"Wrong\";\n})(DataType || (exports.DataType = DataType = {}));\nfunction getSchemaTypes(schema) {\n    const types = getJSONTypes(schema.type);\n    const hasNull = types.includes(\"null\");\n    if (hasNull) {\n        if (schema.nullable === false)\n            throw new Error(\"type: null contradicts nullable: false\");\n    }\n    else {\n        if (!types.length && schema.nullable !== undefined) {\n            throw new Error('\"nullable\" cannot be used without \"type\"');\n        }\n        if (schema.nullable === true)\n            types.push(\"null\");\n    }\n    return types;\n}\nexports.getSchemaTypes = getSchemaTypes;\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nfunction getJSONTypes(ts) {\n    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];\n    if (types.every(rules_1.isJSONType))\n        return types;\n    throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"));\n}\nexports.getJSONTypes = getJSONTypes;\nfunction coerceAndCheckDataType(it, types) {\n    const { gen, data, opts } = it;\n    const coerceTo = coerceToTypes(types, opts.coerceTypes);\n    const checkTypes = types.length > 0 &&\n        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));\n    if (checkTypes) {\n        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);\n        gen.if(wrongType, () => {\n            if (coerceTo.length)\n                coerceData(it, types, coerceTo);\n            else\n                reportTypeError(it);\n        });\n    }\n    return checkTypes;\n}\nexports.coerceAndCheckDataType = coerceAndCheckDataType;\nconst COERCIBLE = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"]);\nfunction coerceToTypes(types, coerceTypes) {\n    return coerceTypes\n        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n        : [];\n}\nfunction coerceData(it, types, coerceTo) {\n    const { gen, data, opts } = it;\n    const dataType = gen.let(\"dataType\", (0, codegen_1._) `typeof ${data}`);\n    const coerced = gen.let(\"coerced\", (0, codegen_1._) `undefined`);\n    if (opts.coerceTypes === \"array\") {\n        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen\n            .assign(data, (0, codegen_1._) `${data}[0]`)\n            .assign(dataType, (0, codegen_1._) `typeof ${data}`)\n            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));\n    }\n    gen.if((0, codegen_1._) `${coerced} !== undefined`);\n    for (const t of coerceTo) {\n        if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n            coerceSpecificType(t);\n        }\n    }\n    gen.else();\n    reportTypeError(it);\n    gen.endIf();\n    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {\n        gen.assign(data, coerced);\n        assignParentData(it, coerced);\n    });\n    function coerceSpecificType(t) {\n        switch (t) {\n            case \"string\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n                    .assign(coerced, (0, codegen_1._) `\"\" + ${data}`)\n                    .elseIf((0, codegen_1._) `${data} === null`)\n                    .assign(coerced, (0, codegen_1._) `\"\"`);\n                return;\n            case \"number\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} == \"boolean\" || ${data} === null\n              || (${dataType} == \"string\" && ${data} && ${data} == +${data})`)\n                    .assign(coerced, (0, codegen_1._) `+${data}`);\n                return;\n            case \"integer\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} === \"boolean\" || ${data} === null\n              || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`)\n                    .assign(coerced, (0, codegen_1._) `+${data}`);\n                return;\n            case \"boolean\":\n                gen\n                    .elseIf((0, codegen_1._) `${data} === \"false\" || ${data} === 0 || ${data} === null`)\n                    .assign(coerced, false)\n                    .elseIf((0, codegen_1._) `${data} === \"true\" || ${data} === 1`)\n                    .assign(coerced, true);\n                return;\n            case \"null\":\n                gen.elseIf((0, codegen_1._) `${data} === \"\" || ${data} === 0 || ${data} === false`);\n                gen.assign(coerced, null);\n                return;\n            case \"array\":\n                gen\n                    .elseIf((0, codegen_1._) `${dataType} === \"string\" || ${dataType} === \"number\"\n              || ${dataType} === \"boolean\" || ${data} === null`)\n                    .assign(coerced, (0, codegen_1._) `[${data}]`);\n        }\n    }\n}\nfunction assignParentData({ gen, parentData, parentDataProperty }, expr) {\n    // TODO use gen.property\n    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));\n}\nfunction checkDataType(dataType, data, strictNums, correct = DataType.Correct) {\n    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;\n    let cond;\n    switch (dataType) {\n        case \"null\":\n            return (0, codegen_1._) `${data} ${EQ} null`;\n        case \"array\":\n            cond = (0, codegen_1._) `Array.isArray(${data})`;\n            break;\n        case \"object\":\n            cond = (0, codegen_1._) `${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`;\n            break;\n        case \"integer\":\n            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);\n            break;\n        case \"number\":\n            cond = numCond();\n            break;\n        default:\n            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;\n    }\n    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);\n    function numCond(_cond = codegen_1.nil) {\n        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == \"number\"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);\n    }\n}\nexports.checkDataType = checkDataType;\nfunction checkDataTypes(dataTypes, data, strictNums, correct) {\n    if (dataTypes.length === 1) {\n        return checkDataType(dataTypes[0], data, strictNums, correct);\n    }\n    let cond;\n    const types = (0, util_1.toHash)(dataTypes);\n    if (types.array && types.object) {\n        const notObj = (0, codegen_1._) `typeof ${data} != \"object\"`;\n        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;\n        delete types.null;\n        delete types.array;\n        delete types.object;\n    }\n    else {\n        cond = codegen_1.nil;\n    }\n    if (types.number)\n        delete types.integer;\n    for (const t in types)\n        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));\n    return cond;\n}\nexports.checkDataTypes = checkDataTypes;\nconst typeError = {\n    message: ({ schema }) => `must be ${schema}`,\n    params: ({ schema, schemaValue }) => typeof schema == \"string\" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,\n};\nfunction reportTypeError(it) {\n    const cxt = getTypeErrorContext(it);\n    (0, errors_1.reportError)(cxt, typeError);\n}\nexports.reportTypeError = reportTypeError;\nfunction getTypeErrorContext(it) {\n    const { gen, data, schema } = it;\n    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, \"type\");\n    return {\n        gen,\n        keyword: \"type\",\n        data,\n        schema: schema.type,\n        schemaCode,\n        schemaValue: schemaCode,\n        parentSchema: schema,\n        params: {},\n        it,\n    };\n}\n//# sourceMappingURL=dataType.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.assignDefaults = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction assignDefaults(it, ty) {\n    const { properties, items } = it.schema;\n    if (ty === \"object\" && properties) {\n        for (const key in properties) {\n            assignDefault(it, key, properties[key].default);\n        }\n    }\n    else if (ty === \"array\" && Array.isArray(items)) {\n        items.forEach((sch, i) => assignDefault(it, i, sch.default));\n    }\n}\nexports.assignDefaults = assignDefaults;\nfunction assignDefault(it, prop, defaultValue) {\n    const { gen, compositeRule, data, opts } = it;\n    if (defaultValue === undefined)\n        return;\n    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;\n    if (compositeRule) {\n        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);\n        return;\n    }\n    let condition = (0, codegen_1._) `${childData} === undefined`;\n    if (opts.useDefaults === \"empty\") {\n        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === \"\"`;\n    }\n    // `${childData} === undefined` +\n    // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);\n}\n//# sourceMappingURL=defaults.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;\nconst codegen_1 = require(\"../compile/codegen\");\nconst util_1 = require(\"../compile/util\");\nconst names_1 = require(\"../compile/names\");\nconst util_2 = require(\"../compile/util\");\nfunction checkReportMissingProp(cxt, prop) {\n    const { gen, data, it } = cxt;\n    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);\n        cxt.error();\n    });\n}\nexports.checkReportMissingProp = checkReportMissingProp;\nfunction checkMissingProp({ gen, data, it: { opts } }, properties, missing) {\n    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));\n}\nexports.checkMissingProp = checkMissingProp;\nfunction reportMissingProp(cxt, missing) {\n    cxt.setParams({ missingProperty: missing }, true);\n    cxt.error();\n}\nexports.reportMissingProp = reportMissingProp;\nfunction hasPropFunc(gen) {\n    return gen.scopeValue(\"func\", {\n        // eslint-disable-next-line @typescript-eslint/unbound-method\n        ref: Object.prototype.hasOwnProperty,\n        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,\n    });\n}\nexports.hasPropFunc = hasPropFunc;\nfunction isOwnProperty(gen, data, property) {\n    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;\n}\nexports.isOwnProperty = isOwnProperty;\nfunction propertyInData(gen, data, property, ownProperties) {\n    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;\n    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;\n}\nexports.propertyInData = propertyInData;\nfunction noPropertyInData(gen, data, property, ownProperties) {\n    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;\n    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;\n}\nexports.noPropertyInData = noPropertyInData;\nfunction allSchemaProperties(schemaMap) {\n    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : [];\n}\nexports.allSchemaProperties = allSchemaProperties;\nfunction schemaProperties(it, schemaMap) {\n    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));\n}\nexports.schemaProperties = schemaProperties;\nfunction callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {\n    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;\n    const valCxt = [\n        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],\n        [names_1.default.parentData, it.parentData],\n        [names_1.default.parentDataProperty, it.parentDataProperty],\n        [names_1.default.rootData, names_1.default.rootData],\n    ];\n    if (it.opts.dynamicRef)\n        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);\n    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;\n    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;\n}\nexports.callValidateCode = callValidateCode;\nconst newRegExp = (0, codegen_1._) `new RegExp`;\nfunction usePattern({ gen, it: { opts } }, pattern) {\n    const u = opts.unicodeRegExp ? \"u\" : \"\";\n    const { regExp } = opts.code;\n    const rx = regExp(pattern, u);\n    return gen.scopeValue(\"pattern\", {\n        key: rx.toString(),\n        ref: rx,\n        code: (0, codegen_1._) `${regExp.code === \"new RegExp\" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,\n    });\n}\nexports.usePattern = usePattern;\nfunction validateArray(cxt) {\n    const { gen, data, keyword, it } = cxt;\n    const valid = gen.name(\"valid\");\n    if (it.allErrors) {\n        const validArr = gen.let(\"valid\", true);\n        validateItems(() => gen.assign(validArr, false));\n        return validArr;\n    }\n    gen.var(valid, true);\n    validateItems(() => gen.break());\n    return valid;\n    function validateItems(notValid) {\n        const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n        gen.forRange(\"i\", 0, len, (i) => {\n            cxt.subschema({\n                keyword,\n                dataProp: i,\n                dataPropType: util_1.Type.Num,\n            }, valid);\n            gen.if((0, codegen_1.not)(valid), notValid);\n        });\n    }\n}\nexports.validateArray = validateArray;\nfunction validateUnion(cxt) {\n    const { gen, schema, keyword, it } = cxt;\n    /* istanbul ignore if */\n    if (!Array.isArray(schema))\n        throw new Error(\"ajv implementation error\");\n    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));\n    if (alwaysValid && !it.opts.unevaluated)\n        return;\n    const valid = gen.let(\"valid\", false);\n    const schValid = gen.name(\"_valid\");\n    gen.block(() => schema.forEach((_sch, i) => {\n        const schCxt = cxt.subschema({\n            keyword,\n            schemaProp: i,\n            compositeRule: true,\n        }, schValid);\n        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);\n        const merged = cxt.mergeValidEvaluated(schCxt, schValid);\n        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n        // or if all properties and items were evaluated (it.props === true && it.items === true)\n        if (!merged)\n            gen.if((0, codegen_1.not)(valid));\n    }));\n    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n}\nexports.validateUnion = validateUnion;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst code_1 = require(\"../../vocabularies/code\");\nconst errors_1 = require(\"../errors\");\nfunction macroKeywordCode(cxt, def) {\n    const { gen, keyword, schema, parentSchema, it } = cxt;\n    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);\n    const schemaRef = useKeyword(gen, keyword, macroSchema);\n    if (it.opts.validateSchema !== false)\n        it.self.validateSchema(macroSchema, true);\n    const valid = gen.name(\"valid\");\n    cxt.subschema({\n        schema: macroSchema,\n        schemaPath: codegen_1.nil,\n        errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n        topSchemaRef: schemaRef,\n        compositeRule: true,\n    }, valid);\n    cxt.pass(valid, () => cxt.error(true));\n}\nexports.macroKeywordCode = macroKeywordCode;\nfunction funcKeywordCode(cxt, def) {\n    var _a;\n    const { gen, keyword, schema, parentSchema, $data, it } = cxt;\n    checkAsyncKeyword(it, def);\n    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;\n    const validateRef = useKeyword(gen, keyword, validate);\n    const valid = gen.let(\"valid\");\n    cxt.block$data(valid, validateKeyword);\n    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);\n    function validateKeyword() {\n        if (def.errors === false) {\n            assignValid();\n            if (def.modifying)\n                modifyData(cxt);\n            reportErrs(() => cxt.error());\n        }\n        else {\n            const ruleErrs = def.async ? validateAsync() : validateSync();\n            if (def.modifying)\n                modifyData(cxt);\n            reportErrs(() => addErrs(cxt, ruleErrs));\n        }\n    }\n    function validateAsync() {\n        const ruleErrs = gen.let(\"ruleErrs\", null);\n        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));\n        return ruleErrs;\n    }\n    function validateSync() {\n        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;\n        gen.assign(validateErrs, null);\n        assignValid(codegen_1.nil);\n        return validateErrs;\n    }\n    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {\n        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;\n        const passSchema = !((\"compile\" in def && !$data) || def.schema === false);\n        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);\n    }\n    function reportErrs(errors) {\n        var _a;\n        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);\n    }\n}\nexports.funcKeywordCode = funcKeywordCode;\nfunction modifyData(cxt) {\n    const { gen, data, it } = cxt;\n    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));\n}\nfunction addErrs(cxt, errs) {\n    const { gen } = cxt;\n    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {\n        gen\n            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)\n            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n        (0, errors_1.extendErrors)(cxt);\n    }, () => cxt.error());\n}\nfunction checkAsyncKeyword({ schemaEnv }, def) {\n    if (def.async && !schemaEnv.$async)\n        throw new Error(\"async keyword in sync schema\");\n}\nfunction useKeyword(gen, keyword, result) {\n    if (result === undefined)\n        throw new Error(`keyword \"${keyword}\" failed to compile`);\n    return gen.scopeValue(\"keyword\", typeof result == \"function\" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });\n}\nfunction validSchemaType(schema, schemaType, allowUndefined = false) {\n    // TODO add tests\n    return (!schemaType.length ||\n        schemaType.some((st) => st === \"array\"\n            ? Array.isArray(schema)\n            : st === \"object\"\n                ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n                : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")));\n}\nexports.validSchemaType = validSchemaType;\nfunction validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {\n    /* istanbul ignore if */\n    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n        throw new Error(\"ajv implementation error\");\n    }\n    const deps = def.dependencies;\n    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`);\n    }\n    if (def.validateSchema) {\n        const valid = def.validateSchema(schema[keyword]);\n        if (!valid) {\n            const msg = `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n                self.errorsText(def.validateSchema.errors);\n            if (opts.validateSchema === \"log\")\n                self.logger.error(msg);\n            else\n                throw new Error(msg);\n        }\n    }\n}\nexports.validateKeywordUsage = validateKeywordUsage;\n//# sourceMappingURL=keyword.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {\n    if (keyword !== undefined && schema !== undefined) {\n        throw new Error('both \"keyword\" and \"schema\" passed, only one allowed');\n    }\n    if (keyword !== undefined) {\n        const sch = it.schema[keyword];\n        return schemaProp === undefined\n            ? {\n                schema: sch,\n                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,\n                errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n            }\n            : {\n                schema: sch[schemaProp],\n                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,\n                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,\n            };\n    }\n    if (schema !== undefined) {\n        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n            throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"');\n        }\n        return {\n            schema,\n            schemaPath,\n            topSchemaRef,\n            errSchemaPath,\n        };\n    }\n    throw new Error('either \"keyword\" or \"schema\" must be passed');\n}\nexports.getSubschema = getSubschema;\nfunction extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {\n    if (data !== undefined && dataProp !== undefined) {\n        throw new Error('both \"data\" and \"dataProp\" passed, only one allowed');\n    }\n    const { gen } = it;\n    if (dataProp !== undefined) {\n        const { errorPath, dataPathArr, opts } = it;\n        const nextData = gen.let(\"data\", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);\n        dataContextProps(nextData);\n        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;\n        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;\n        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];\n    }\n    if (data !== undefined) {\n        const nextData = data instanceof codegen_1.Name ? data : gen.let(\"data\", data, true); // replaceable if used once?\n        dataContextProps(nextData);\n        if (propertyName !== undefined)\n            subschema.propertyName = propertyName;\n        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n    }\n    if (dataTypes)\n        subschema.dataTypes = dataTypes;\n    function dataContextProps(_nextData) {\n        subschema.data = _nextData;\n        subschema.dataLevel = it.dataLevel + 1;\n        subschema.dataTypes = [];\n        it.definedProperties = new Set();\n        subschema.parentData = it.data;\n        subschema.dataNames = [...it.dataNames, _nextData];\n    }\n}\nexports.extendSubschemaData = extendSubschemaData;\nfunction extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {\n    if (compositeRule !== undefined)\n        subschema.compositeRule = compositeRule;\n    if (createErrors !== undefined)\n        subschema.createErrors = createErrors;\n    if (allErrors !== undefined)\n        subschema.allErrors = allErrors;\n    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited\n    subschema.jtdMetadata = jtdMetadata; // not inherited\n}\nexports.extendSubschemaMode = extendSubschemaMode;\n//# sourceMappingURL=subschema.js.map","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n  if (a === b) return true;\n\n  if (a && b && typeof a == 'object' && typeof b == 'object') {\n    if (a.constructor !== b.constructor) return false;\n\n    var length, i, keys;\n    if (Array.isArray(a)) {\n      length = a.length;\n      if (length != b.length) return false;\n      for (i = length; i-- !== 0;)\n        if (!equal(a[i], b[i])) return false;\n      return true;\n    }\n\n\n\n    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n    keys = Object.keys(a);\n    length = keys.length;\n    if (length !== Object.keys(b).length) return false;\n\n    for (i = length; i-- !== 0;)\n      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n    for (i = length; i-- !== 0;) {\n      var key = keys[i];\n\n      if (!equal(a[key], b[key])) return false;\n    }\n\n    return true;\n  }\n\n  // true if both NaN, false otherwise\n  return a!==a && b!==b;\n};\n","'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n  // Legacy support for v0.3.1 and earlier.\n  if (typeof opts == 'function') {\n    cb = opts;\n    opts = {};\n  }\n\n  cb = opts.cb || cb;\n  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n  var post = cb.post || function() {};\n\n  _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n  additionalItems: true,\n  items: true,\n  contains: true,\n  additionalProperties: true,\n  propertyNames: true,\n  not: true,\n  if: true,\n  then: true,\n  else: true\n};\n\ntraverse.arrayKeywords = {\n  items: true,\n  allOf: true,\n  anyOf: true,\n  oneOf: true\n};\n\ntraverse.propsKeywords = {\n  $defs: true,\n  definitions: true,\n  properties: true,\n  patternProperties: true,\n  dependencies: true\n};\n\ntraverse.skipKeywords = {\n  default: true,\n  enum: true,\n  const: true,\n  required: true,\n  maximum: true,\n  minimum: true,\n  exclusiveMaximum: true,\n  exclusiveMinimum: true,\n  multipleOf: true,\n  maxLength: true,\n  minLength: true,\n  pattern: true,\n  format: true,\n  maxItems: true,\n  minItems: true,\n  uniqueItems: true,\n  maxProperties: true,\n  minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n    for (var key in schema) {\n      var sch = schema[key];\n      if (Array.isArray(sch)) {\n        if (key in traverse.arrayKeywords) {\n          for (var i=0; i<sch.length; i++)\n            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n        }\n      } else if (key in traverse.propsKeywords) {\n        if (sch && typeof sch == 'object') {\n          for (var prop in sch)\n            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n        }\n      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n      }\n    }\n    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n  }\n}\n\n\nfunction escapeJsonPtr(str) {\n  return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;\nconst util_1 = require(\"./util\");\nconst equal = require(\"fast-deep-equal\");\nconst traverse = require(\"json-schema-traverse\");\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n    \"type\",\n    \"format\",\n    \"pattern\",\n    \"maxLength\",\n    \"minLength\",\n    \"maxProperties\",\n    \"minProperties\",\n    \"maxItems\",\n    \"minItems\",\n    \"maximum\",\n    \"minimum\",\n    \"uniqueItems\",\n    \"multipleOf\",\n    \"required\",\n    \"enum\",\n    \"const\",\n]);\nfunction inlineRef(schema, limit = true) {\n    if (typeof schema == \"boolean\")\n        return true;\n    if (limit === true)\n        return !hasRef(schema);\n    if (!limit)\n        return false;\n    return countKeys(schema) <= limit;\n}\nexports.inlineRef = inlineRef;\nconst REF_KEYWORDS = new Set([\n    \"$ref\",\n    \"$recursiveRef\",\n    \"$recursiveAnchor\",\n    \"$dynamicRef\",\n    \"$dynamicAnchor\",\n]);\nfunction hasRef(schema) {\n    for (const key in schema) {\n        if (REF_KEYWORDS.has(key))\n            return true;\n        const sch = schema[key];\n        if (Array.isArray(sch) && sch.some(hasRef))\n            return true;\n        if (typeof sch == \"object\" && hasRef(sch))\n            return true;\n    }\n    return false;\n}\nfunction countKeys(schema) {\n    let count = 0;\n    for (const key in schema) {\n        if (key === \"$ref\")\n            return Infinity;\n        count++;\n        if (SIMPLE_INLINED.has(key))\n            continue;\n        if (typeof schema[key] == \"object\") {\n            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));\n        }\n        if (count === Infinity)\n            return Infinity;\n    }\n    return count;\n}\nfunction getFullPath(resolver, id = \"\", normalize) {\n    if (normalize !== false)\n        id = normalizeId(id);\n    const p = resolver.parse(id);\n    return _getFullPath(resolver, p);\n}\nexports.getFullPath = getFullPath;\nfunction _getFullPath(resolver, p) {\n    const serialized = resolver.serialize(p);\n    return serialized.split(\"#\")[0] + \"#\";\n}\nexports._getFullPath = _getFullPath;\nconst TRAILING_SLASH_HASH = /#\\/?$/;\nfunction normalizeId(id) {\n    return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\";\n}\nexports.normalizeId = normalizeId;\nfunction resolveUrl(resolver, baseId, id) {\n    id = normalizeId(id);\n    return resolver.resolve(baseId, id);\n}\nexports.resolveUrl = resolveUrl;\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i;\nfunction getSchemaRefs(schema, baseId) {\n    if (typeof schema == \"boolean\")\n        return {};\n    const { schemaId, uriResolver } = this.opts;\n    const schId = normalizeId(schema[schemaId] || baseId);\n    const baseIds = { \"\": schId };\n    const pathPrefix = getFullPath(uriResolver, schId, false);\n    const localRefs = {};\n    const schemaRefs = new Set();\n    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {\n        if (parentJsonPtr === undefined)\n            return;\n        const fullPath = pathPrefix + jsonPtr;\n        let innerBaseId = baseIds[parentJsonPtr];\n        if (typeof sch[schemaId] == \"string\")\n            innerBaseId = addRef.call(this, sch[schemaId]);\n        addAnchor.call(this, sch.$anchor);\n        addAnchor.call(this, sch.$dynamicAnchor);\n        baseIds[jsonPtr] = innerBaseId;\n        function addRef(ref) {\n            // eslint-disable-next-line @typescript-eslint/unbound-method\n            const _resolve = this.opts.uriResolver.resolve;\n            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);\n            if (schemaRefs.has(ref))\n                throw ambiguos(ref);\n            schemaRefs.add(ref);\n            let schOrRef = this.refs[ref];\n            if (typeof schOrRef == \"string\")\n                schOrRef = this.refs[schOrRef];\n            if (typeof schOrRef == \"object\") {\n                checkAmbiguosRef(sch, schOrRef.schema, ref);\n            }\n            else if (ref !== normalizeId(fullPath)) {\n                if (ref[0] === \"#\") {\n                    checkAmbiguosRef(sch, localRefs[ref], ref);\n                    localRefs[ref] = sch;\n                }\n                else {\n                    this.refs[ref] = fullPath;\n                }\n            }\n            return ref;\n        }\n        function addAnchor(anchor) {\n            if (typeof anchor == \"string\") {\n                if (!ANCHOR.test(anchor))\n                    throw new Error(`invalid anchor \"${anchor}\"`);\n                addRef.call(this, `#${anchor}`);\n            }\n        }\n    });\n    return localRefs;\n    function checkAmbiguosRef(sch1, sch2, ref) {\n        if (sch2 !== undefined && !equal(sch1, sch2))\n            throw ambiguos(ref);\n    }\n    function ambiguos(ref) {\n        return new Error(`reference \"${ref}\" resolves to more than one schema`);\n    }\n}\nexports.getSchemaRefs = getSchemaRefs;\n//# sourceMappingURL=resolve.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;\nconst boolSchema_1 = require(\"./boolSchema\");\nconst dataType_1 = require(\"./dataType\");\nconst applicability_1 = require(\"./applicability\");\nconst dataType_2 = require(\"./dataType\");\nconst defaults_1 = require(\"./defaults\");\nconst keyword_1 = require(\"./keyword\");\nconst subschema_1 = require(\"./subschema\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst resolve_1 = require(\"../resolve\");\nconst util_1 = require(\"../util\");\nconst errors_1 = require(\"../errors\");\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nfunction validateFunctionCode(it) {\n    if (isSchemaObj(it)) {\n        checkKeywords(it);\n        if (schemaCxtHasRules(it)) {\n            topSchemaObjCode(it);\n            return;\n        }\n    }\n    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));\n}\nexports.validateFunctionCode = validateFunctionCode;\nfunction validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {\n    if (opts.code.es5) {\n        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {\n            gen.code((0, codegen_1._) `\"use strict\"; ${funcSourceUrl(schema, opts)}`);\n            destructureValCxtES5(gen, opts);\n            gen.code(body);\n        });\n    }\n    else {\n        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));\n    }\n}\nfunction destructureValCxt(opts) {\n    return (0, codegen_1._) `{${names_1.default.instancePath}=\"\", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;\n}\nfunction destructureValCxtES5(gen, opts) {\n    gen.if(names_1.default.valCxt, () => {\n        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);\n        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);\n        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);\n        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);\n        if (opts.dynamicRef)\n            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);\n    }, () => {\n        gen.var(names_1.default.instancePath, (0, codegen_1._) `\"\"`);\n        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);\n        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);\n        gen.var(names_1.default.rootData, names_1.default.data);\n        if (opts.dynamicRef)\n            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);\n    });\n}\nfunction topSchemaObjCode(it) {\n    const { schema, opts, gen } = it;\n    validateFunction(it, () => {\n        if (opts.$comment && schema.$comment)\n            commentKeyword(it);\n        checkNoDefault(it);\n        gen.let(names_1.default.vErrors, null);\n        gen.let(names_1.default.errors, 0);\n        if (opts.unevaluated)\n            resetEvaluated(it);\n        typeAndKeywords(it);\n        returnResults(it);\n    });\n    return;\n}\nfunction resetEvaluated(it) {\n    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n    const { gen, validateName } = it;\n    it.evaluated = gen.const(\"evaluated\", (0, codegen_1._) `${validateName}.evaluated`);\n    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));\n    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));\n}\nfunction funcSourceUrl(schema, opts) {\n    const schId = typeof schema == \"object\" && schema[opts.schemaId];\n    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;\n}\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it, valid) {\n    if (isSchemaObj(it)) {\n        checkKeywords(it);\n        if (schemaCxtHasRules(it)) {\n            subSchemaObjCode(it, valid);\n            return;\n        }\n    }\n    (0, boolSchema_1.boolOrEmptySchema)(it, valid);\n}\nfunction schemaCxtHasRules({ schema, self }) {\n    if (typeof schema == \"boolean\")\n        return !schema;\n    for (const key in schema)\n        if (self.RULES.all[key])\n            return true;\n    return false;\n}\nfunction isSchemaObj(it) {\n    return typeof it.schema != \"boolean\";\n}\nfunction subSchemaObjCode(it, valid) {\n    const { schema, gen, opts } = it;\n    if (opts.$comment && schema.$comment)\n        commentKeyword(it);\n    updateContext(it);\n    checkAsyncSchema(it);\n    const errsCount = gen.const(\"_errs\", names_1.default.errors);\n    typeAndKeywords(it, errsCount);\n    // TODO var\n    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n}\nfunction checkKeywords(it) {\n    (0, util_1.checkUnknownRules)(it);\n    checkRefsAndKeywords(it);\n}\nfunction typeAndKeywords(it, errsCount) {\n    if (it.opts.jtd)\n        return schemaKeywords(it, [], false, errsCount);\n    const types = (0, dataType_1.getSchemaTypes)(it.schema);\n    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);\n    schemaKeywords(it, types, !checkedTypes, errsCount);\n}\nfunction checkRefsAndKeywords(it) {\n    const { schema, errSchemaPath, opts, self } = it;\n    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {\n        self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`);\n    }\n}\nfunction checkNoDefault(it) {\n    const { schema, opts } = it;\n    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n        (0, util_1.checkStrictMode)(it, \"default is ignored in the schema root\");\n    }\n}\nfunction updateContext(it) {\n    const schId = it.schema[it.opts.schemaId];\n    if (schId)\n        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);\n}\nfunction checkAsyncSchema(it) {\n    if (it.schema.$async && !it.schemaEnv.$async)\n        throw new Error(\"async schema in sync schema\");\n}\nfunction commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {\n    const msg = schema.$comment;\n    if (opts.$comment === true) {\n        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);\n    }\n    else if (typeof opts.$comment == \"function\") {\n        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;\n        const rootName = gen.scopeValue(\"root\", { ref: schemaEnv.root });\n        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);\n    }\n}\nfunction returnResults(it) {\n    const { gen, schemaEnv, validateName, ValidationError, opts } = it;\n    if (schemaEnv.$async) {\n        // TODO assign unevaluated\n        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));\n    }\n    else {\n        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);\n        if (opts.unevaluated)\n            assignEvaluated(it);\n        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);\n    }\n}\nfunction assignEvaluated({ gen, evaluated, props, items }) {\n    if (props instanceof codegen_1.Name)\n        gen.assign((0, codegen_1._) `${evaluated}.props`, props);\n    if (items instanceof codegen_1.Name)\n        gen.assign((0, codegen_1._) `${evaluated}.items`, items);\n}\nfunction schemaKeywords(it, types, typeErrors, errsCount) {\n    const { gen, schema, data, allErrors, opts, self } = it;\n    const { RULES } = self;\n    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {\n        gen.block(() => keywordCode(it, \"$ref\", RULES.all.$ref.definition)); // TODO typecast\n        return;\n    }\n    if (!opts.jtd)\n        checkStrictTypes(it, types);\n    gen.block(() => {\n        for (const group of RULES.rules)\n            groupKeywords(group);\n        groupKeywords(RULES.post);\n    });\n    function groupKeywords(group) {\n        if (!(0, applicability_1.shouldUseGroup)(schema, group))\n            return;\n        if (group.type) {\n            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));\n            iterateKeywords(it, group);\n            if (types.length === 1 && types[0] === group.type && typeErrors) {\n                gen.else();\n                (0, dataType_2.reportTypeError)(it);\n            }\n            gen.endIf();\n        }\n        else {\n            iterateKeywords(it, group);\n        }\n        // TODO make it \"ok\" call?\n        if (!allErrors)\n            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);\n    }\n}\nfunction iterateKeywords(it, group) {\n    const { gen, schema, opts: { useDefaults }, } = it;\n    if (useDefaults)\n        (0, defaults_1.assignDefaults)(it, group.type);\n    gen.block(() => {\n        for (const rule of group.rules) {\n            if ((0, applicability_1.shouldUseRule)(schema, rule)) {\n                keywordCode(it, rule.keyword, rule.definition, group.type);\n            }\n        }\n    });\n}\nfunction checkStrictTypes(it, types) {\n    if (it.schemaEnv.meta || !it.opts.strictTypes)\n        return;\n    checkContextTypes(it, types);\n    if (!it.opts.allowUnionTypes)\n        checkMultipleTypes(it, types);\n    checkKeywordTypes(it, it.dataTypes);\n}\nfunction checkContextTypes(it, types) {\n    if (!types.length)\n        return;\n    if (!it.dataTypes.length) {\n        it.dataTypes = types;\n        return;\n    }\n    types.forEach((t) => {\n        if (!includesType(it.dataTypes, t)) {\n            strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`);\n        }\n    });\n    narrowSchemaTypes(it, types);\n}\nfunction checkMultipleTypes(it, ts) {\n    if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n        strictTypesError(it, \"use allowUnionTypes to allow union type keyword\");\n    }\n}\nfunction checkKeywordTypes(it, ts) {\n    const rules = it.self.RULES.all;\n    for (const keyword in rules) {\n        const rule = rules[keyword];\n        if (typeof rule == \"object\" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {\n            const { type } = rule.definition;\n            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n                strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`);\n            }\n        }\n    }\n}\nfunction hasApplicableType(schTs, kwdT) {\n    return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"));\n}\nfunction includesType(ts, t) {\n    return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"));\n}\nfunction narrowSchemaTypes(it, withTypes) {\n    const ts = [];\n    for (const t of it.dataTypes) {\n        if (includesType(withTypes, t))\n            ts.push(t);\n        else if (withTypes.includes(\"integer\") && t === \"number\")\n            ts.push(\"integer\");\n    }\n    it.dataTypes = ts;\n}\nfunction strictTypesError(it, msg) {\n    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n    msg += ` at \"${schemaPath}\" (strictTypes)`;\n    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);\n}\nclass KeywordCxt {\n    constructor(it, def, keyword) {\n        (0, keyword_1.validateKeywordUsage)(it, def, keyword);\n        this.gen = it.gen;\n        this.allErrors = it.allErrors;\n        this.keyword = keyword;\n        this.data = it.data;\n        this.schema = it.schema[keyword];\n        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;\n        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);\n        this.schemaType = def.schemaType;\n        this.parentSchema = it.schema;\n        this.params = {};\n        this.it = it;\n        this.def = def;\n        if (this.$data) {\n            this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it));\n        }\n        else {\n            this.schemaCode = this.schemaValue;\n            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {\n                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);\n            }\n        }\n        if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n            this.errsCount = it.gen.const(\"_errs\", names_1.default.errors);\n        }\n    }\n    result(condition, successAction, failAction) {\n        this.failResult((0, codegen_1.not)(condition), successAction, failAction);\n    }\n    failResult(condition, successAction, failAction) {\n        this.gen.if(condition);\n        if (failAction)\n            failAction();\n        else\n            this.error();\n        if (successAction) {\n            this.gen.else();\n            successAction();\n            if (this.allErrors)\n                this.gen.endIf();\n        }\n        else {\n            if (this.allErrors)\n                this.gen.endIf();\n            else\n                this.gen.else();\n        }\n    }\n    pass(condition, failAction) {\n        this.failResult((0, codegen_1.not)(condition), undefined, failAction);\n    }\n    fail(condition) {\n        if (condition === undefined) {\n            this.error();\n            if (!this.allErrors)\n                this.gen.if(false); // this branch will be removed by gen.optimize\n            return;\n        }\n        this.gen.if(condition);\n        this.error();\n        if (this.allErrors)\n            this.gen.endIf();\n        else\n            this.gen.else();\n    }\n    fail$data(condition) {\n        if (!this.$data)\n            return this.fail(condition);\n        const { schemaCode } = this;\n        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);\n    }\n    error(append, errorParams, errorPaths) {\n        if (errorParams) {\n            this.setParams(errorParams);\n            this._error(append, errorPaths);\n            this.setParams({});\n            return;\n        }\n        this._error(append, errorPaths);\n    }\n    _error(append, errorPaths) {\n        ;\n        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);\n    }\n    $dataError() {\n        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);\n    }\n    reset() {\n        if (this.errsCount === undefined)\n            throw new Error('add \"trackErrors\" to keyword definition');\n        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);\n    }\n    ok(cond) {\n        if (!this.allErrors)\n            this.gen.if(cond);\n    }\n    setParams(obj, assign) {\n        if (assign)\n            Object.assign(this.params, obj);\n        else\n            this.params = obj;\n    }\n    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {\n        this.gen.block(() => {\n            this.check$data(valid, $dataValid);\n            codeBlock();\n        });\n    }\n    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {\n        if (!this.$data)\n            return;\n        const { gen, schemaCode, schemaType, def } = this;\n        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));\n        if (valid !== codegen_1.nil)\n            gen.assign(valid, true);\n        if (schemaType.length || def.validateSchema) {\n            gen.elseIf(this.invalid$data());\n            this.$dataError();\n            if (valid !== codegen_1.nil)\n                gen.assign(valid, false);\n        }\n        gen.else();\n    }\n    invalid$data() {\n        const { gen, schemaCode, schemaType, def, it } = this;\n        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());\n        function wrong$DataType() {\n            if (schemaType.length) {\n                /* istanbul ignore if */\n                if (!(schemaCode instanceof codegen_1.Name))\n                    throw new Error(\"ajv implementation error\");\n                const st = Array.isArray(schemaType) ? schemaType : [schemaType];\n                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;\n            }\n            return codegen_1.nil;\n        }\n        function invalid$DataSchema() {\n            if (def.validateSchema) {\n                const validateSchemaRef = gen.scopeValue(\"validate$data\", { ref: def.validateSchema }); // TODO value.code for standalone\n                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;\n            }\n            return codegen_1.nil;\n        }\n    }\n    subschema(appl, valid) {\n        const subschema = (0, subschema_1.getSubschema)(this.it, appl);\n        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);\n        (0, subschema_1.extendSubschemaMode)(subschema, appl);\n        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };\n        subschemaCode(nextContext, valid);\n        return nextContext;\n    }\n    mergeEvaluated(schemaCxt, toName) {\n        const { it, gen } = this;\n        if (!it.opts.unevaluated)\n            return;\n        if (it.props !== true && schemaCxt.props !== undefined) {\n            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);\n        }\n        if (it.items !== true && schemaCxt.items !== undefined) {\n            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);\n        }\n    }\n    mergeValidEvaluated(schemaCxt, valid) {\n        const { it, gen } = this;\n        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));\n            return true;\n        }\n    }\n}\nexports.KeywordCxt = KeywordCxt;\nfunction keywordCode(it, keyword, def, ruleType) {\n    const cxt = new KeywordCxt(it, def, keyword);\n    if (\"code\" in def) {\n        def.code(cxt, ruleType);\n    }\n    else if (cxt.$data && def.validate) {\n        (0, keyword_1.funcKeywordCode)(cxt, def);\n    }\n    else if (\"macro\" in def) {\n        (0, keyword_1.macroKeywordCode)(cxt, def);\n    }\n    else if (def.compile || def.validate) {\n        (0, keyword_1.funcKeywordCode)(cxt, def);\n    }\n}\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/;\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/;\nfunction getData($data, { dataLevel, dataNames, dataPathArr }) {\n    let jsonPointer;\n    let data;\n    if ($data === \"\")\n        return names_1.default.rootData;\n    if ($data[0] === \"/\") {\n        if (!JSON_POINTER.test($data))\n            throw new Error(`Invalid JSON-pointer: ${$data}`);\n        jsonPointer = $data;\n        data = names_1.default.rootData;\n    }\n    else {\n        const matches = RELATIVE_JSON_POINTER.exec($data);\n        if (!matches)\n            throw new Error(`Invalid JSON-pointer: ${$data}`);\n        const up = +matches[1];\n        jsonPointer = matches[2];\n        if (jsonPointer === \"#\") {\n            if (up >= dataLevel)\n                throw new Error(errorMsg(\"property/index\", up));\n            return dataPathArr[dataLevel - up];\n        }\n        if (up > dataLevel)\n            throw new Error(errorMsg(\"data\", up));\n        data = dataNames[dataLevel - up];\n        if (!jsonPointer)\n            return data;\n    }\n    let expr = data;\n    const segments = jsonPointer.split(\"/\");\n    for (const segment of segments) {\n        if (segment) {\n            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;\n            expr = (0, codegen_1._) `${expr} && ${data}`;\n        }\n    }\n    return expr;\n    function errorMsg(pointerType, up) {\n        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;\n    }\n}\nexports.getData = getData;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass ValidationError extends Error {\n    constructor(errors) {\n        super(\"validation failed\");\n        this.errors = errors;\n        this.ajv = this.validation = true;\n    }\n}\nexports.default = ValidationError;\n//# sourceMappingURL=validation_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst resolve_1 = require(\"./resolve\");\nclass MissingRefError extends Error {\n    constructor(resolver, baseId, ref, msg) {\n        super(msg || `can't resolve reference ${ref} from id ${baseId}`);\n        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);\n        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));\n    }\n}\nexports.default = MissingRefError;\n//# sourceMappingURL=ref_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst validation_error_1 = require(\"../runtime/validation_error\");\nconst names_1 = require(\"./names\");\nconst resolve_1 = require(\"./resolve\");\nconst util_1 = require(\"./util\");\nconst validate_1 = require(\"./validate\");\nclass SchemaEnv {\n    constructor(env) {\n        var _a;\n        this.refs = {};\n        this.dynamicAnchors = {};\n        let schema;\n        if (typeof env.schema == \"object\")\n            schema = env.schema;\n        this.schema = env.schema;\n        this.schemaId = env.schemaId;\n        this.root = env.root || this;\n        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || \"$id\"]);\n        this.schemaPath = env.schemaPath;\n        this.localRefs = env.localRefs;\n        this.meta = env.meta;\n        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;\n        this.refs = {};\n    }\n}\nexports.SchemaEnv = SchemaEnv;\n// let codeSize = 0\n// let nodeCount = 0\n// Compiles schema in SchemaEnv\nfunction compileSchema(sch) {\n    // TODO refactor - remove compilations\n    const _sch = getCompilingSchema.call(this, sch);\n    if (_sch)\n        return _sch;\n    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails\n    const { es5, lines } = this.opts.code;\n    const { ownProperties } = this.opts;\n    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });\n    let _ValidationError;\n    if (sch.$async) {\n        _ValidationError = gen.scopeValue(\"Error\", {\n            ref: validation_error_1.default,\n            code: (0, codegen_1._) `require(\"ajv/dist/runtime/validation_error\").default`,\n        });\n    }\n    const validateName = gen.scopeName(\"validate\");\n    sch.validateName = validateName;\n    const schemaCxt = {\n        gen,\n        allErrors: this.opts.allErrors,\n        data: names_1.default.data,\n        parentData: names_1.default.parentData,\n        parentDataProperty: names_1.default.parentDataProperty,\n        dataNames: [names_1.default.data],\n        dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?\n        dataLevel: 0,\n        dataTypes: [],\n        definedProperties: new Set(),\n        topSchemaRef: gen.scopeValue(\"schema\", this.opts.code.source === true\n            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }\n            : { ref: sch.schema }),\n        validateName,\n        ValidationError: _ValidationError,\n        schema: sch.schema,\n        schemaEnv: sch,\n        rootId,\n        baseId: sch.baseId || rootId,\n        schemaPath: codegen_1.nil,\n        errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n        errorPath: (0, codegen_1._) `\"\"`,\n        opts: this.opts,\n        self: this,\n    };\n    let sourceCode;\n    try {\n        this._compilations.add(sch);\n        (0, validate_1.validateFunctionCode)(schemaCxt);\n        gen.optimize(this.opts.code.optimize);\n        // gen.optimize(1)\n        const validateCode = gen.toString();\n        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;\n        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n        if (this.opts.code.process)\n            sourceCode = this.opts.code.process(sourceCode, sch);\n        // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);\n        const validate = makeValidate(this, this.scope.get());\n        this.scope.value(validateName, { ref: validate });\n        validate.errors = null;\n        validate.schema = sch.schema;\n        validate.schemaEnv = sch;\n        if (sch.$async)\n            validate.$async = true;\n        if (this.opts.code.source === true) {\n            validate.source = { validateName, validateCode, scopeValues: gen._values };\n        }\n        if (this.opts.unevaluated) {\n            const { props, items } = schemaCxt;\n            validate.evaluated = {\n                props: props instanceof codegen_1.Name ? undefined : props,\n                items: items instanceof codegen_1.Name ? undefined : items,\n                dynamicProps: props instanceof codegen_1.Name,\n                dynamicItems: items instanceof codegen_1.Name,\n            };\n            if (validate.source)\n                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);\n        }\n        sch.validate = validate;\n        return sch;\n    }\n    catch (e) {\n        delete sch.validate;\n        delete sch.validateName;\n        if (sourceCode)\n            this.logger.error(\"Error compiling schema, function code:\", sourceCode);\n        // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n        throw e;\n    }\n    finally {\n        this._compilations.delete(sch);\n    }\n}\nexports.compileSchema = compileSchema;\nfunction resolveRef(root, baseId, ref) {\n    var _a;\n    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);\n    const schOrFunc = root.refs[ref];\n    if (schOrFunc)\n        return schOrFunc;\n    let _sch = resolve.call(this, root, ref);\n    if (_sch === undefined) {\n        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv\n        const { schemaId } = this.opts;\n        if (schema)\n            _sch = new SchemaEnv({ schema, schemaId, root, baseId });\n    }\n    if (_sch === undefined)\n        return;\n    return (root.refs[ref] = inlineOrCompile.call(this, _sch));\n}\nexports.resolveRef = resolveRef;\nfunction inlineOrCompile(sch) {\n    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))\n        return sch.schema;\n    return sch.validate ? sch : compileSchema.call(this, sch);\n}\n// Index of schema compilation in the currently compiled list\nfunction getCompilingSchema(schEnv) {\n    for (const sch of this._compilations) {\n        if (sameSchemaEnv(sch, schEnv))\n            return sch;\n    }\n}\nexports.getCompilingSchema = getCompilingSchema;\nfunction sameSchemaEnv(s1, s2) {\n    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;\n}\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(root, // information about the root schema for the current schema\nref // reference to resolve\n) {\n    let sch;\n    while (typeof (sch = this.refs[ref]) == \"string\")\n        ref = sch;\n    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);\n}\n// Resolve schema, its root and baseId\nfunction resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\nref // reference to resolve\n) {\n    const p = this.opts.uriResolver.parse(ref);\n    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);\n    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);\n    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n    if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n        return getJsonPointer.call(this, p, root);\n    }\n    const id = (0, resolve_1.normalizeId)(refPath);\n    const schOrRef = this.refs[id] || this.schemas[id];\n    if (typeof schOrRef == \"string\") {\n        const sch = resolveSchema.call(this, root, schOrRef);\n        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== \"object\")\n            return;\n        return getJsonPointer.call(this, p, sch);\n    }\n    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== \"object\")\n        return;\n    if (!schOrRef.validate)\n        compileSchema.call(this, schOrRef);\n    if (id === (0, resolve_1.normalizeId)(ref)) {\n        const { schema } = schOrRef;\n        const { schemaId } = this.opts;\n        const schId = schema[schemaId];\n        if (schId)\n            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n        return new SchemaEnv({ schema, schemaId, root, baseId });\n    }\n    return getJsonPointer.call(this, p, schOrRef);\n}\nexports.resolveSchema = resolveSchema;\nconst PREVENT_SCOPE_CHANGE = new Set([\n    \"properties\",\n    \"patternProperties\",\n    \"enum\",\n    \"dependencies\",\n    \"definitions\",\n]);\nfunction getJsonPointer(parsedRef, { baseId, schema, root }) {\n    var _a;\n    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== \"/\")\n        return;\n    for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n        if (typeof schema === \"boolean\")\n            return;\n        const partSchema = schema[(0, util_1.unescapeFragment)(part)];\n        if (partSchema === undefined)\n            return;\n        schema = partSchema;\n        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n        const schId = typeof schema === \"object\" && schema[this.opts.schemaId];\n        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n        }\n    }\n    let env;\n    if (typeof schema != \"boolean\" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {\n        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);\n        env = resolveSchema.call(this, root, $ref);\n    }\n    // even though resolution failed we need to return SchemaEnv to throw exception\n    // so that compileAsync loads missing schema.\n    const { schemaId } = this.opts;\n    env = env || new SchemaEnv({ schema, schemaId, root, baseId });\n    if (env.schema !== env.root.schema)\n        return env;\n    return undefined;\n}\n//# sourceMappingURL=index.js.map","","'use strict'\n\n/** @type {(value: string) => boolean} */\nconst isUUID = RegExp.prototype.test.bind(/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)$/u)\n\n/** @type {(value: string) => boolean} */\nconst isHexPair = RegExp.prototype.test.bind(/^[\\da-f]{2}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isUnreserved = RegExp.prototype.test.bind(/^[\\da-z\\-._~]$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isPathCharacter = RegExp.prototype.test.bind(/^[\\da-z\\-._~!$&'()*+,;=:@/]$/iu)\n\n/**\n * @param {Array<string>} input\n * @returns {string}\n */\nfunction stringArrayToHexStripped (input) {\n  let acc = ''\n  let code = 0\n  let i = 0\n\n  for (i = 0; i < input.length; i++) {\n    code = input[i].charCodeAt(0)\n    if (code === 48) {\n      continue\n    }\n    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n      return ''\n    }\n    acc += input[i]\n    break\n  }\n\n  for (i += 1; i < input.length; i++) {\n    code = input[i].charCodeAt(0)\n    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n      return ''\n    }\n    acc += input[i]\n  }\n  return acc\n}\n\n/**\n * @typedef {Object} GetIPV6Result\n * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.\n * @property {string} address - The parsed IPv6 address.\n * @property {string} [zone] - The zone identifier, if present.\n */\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nconst nonSimpleDomain = RegExp.prototype.test.bind(/[^!\"$&'()*+,\\-.;=_`a-z{}~]/u)\n\n/**\n * @param {Array<string>} buffer\n * @returns {boolean}\n */\nfunction consumeIsZone (buffer) {\n  buffer.length = 0\n  return true\n}\n\n/**\n * @param {Array<string>} buffer\n * @param {Array<string>} address\n * @param {GetIPV6Result} output\n * @returns {boolean}\n */\nfunction consumeHextets (buffer, address, output) {\n  if (buffer.length) {\n    const hex = stringArrayToHexStripped(buffer)\n    if (hex !== '') {\n      address.push(hex)\n    } else {\n      output.error = true\n      return false\n    }\n    buffer.length = 0\n  }\n  return true\n}\n\n/**\n * @param {string} input\n * @returns {GetIPV6Result}\n */\nfunction getIPV6 (input) {\n  let tokenCount = 0\n  const output = { error: false, address: '', zone: '' }\n  /** @type {Array<string>} */\n  const address = []\n  /** @type {Array<string>} */\n  const buffer = []\n  let endipv6Encountered = false\n  let endIpv6 = false\n\n  let consume = consumeHextets\n\n  for (let i = 0; i < input.length; i++) {\n    const cursor = input[i]\n    if (cursor === '[' || cursor === ']') { continue }\n    if (cursor === ':') {\n      if (endipv6Encountered === true) {\n        endIpv6 = true\n      }\n      if (!consume(buffer, address, output)) { break }\n      if (++tokenCount > 7) {\n        // not valid\n        output.error = true\n        break\n      }\n      if (i > 0 && input[i - 1] === ':') {\n        endipv6Encountered = true\n      }\n      address.push(':')\n      continue\n    } else if (cursor === '%') {\n      if (!consume(buffer, address, output)) { break }\n      // switch to zone detection\n      consume = consumeIsZone\n    } else {\n      buffer.push(cursor)\n      continue\n    }\n  }\n  if (buffer.length) {\n    if (consume === consumeIsZone) {\n      output.zone = buffer.join('')\n    } else if (endIpv6) {\n      address.push(buffer.join(''))\n    } else {\n      address.push(stringArrayToHexStripped(buffer))\n    }\n  }\n  output.address = address.join('')\n  return output\n}\n\n/**\n * @typedef {Object} NormalizeIPv6Result\n * @property {string} host - The normalized host.\n * @property {string} [escapedHost] - The escaped host.\n * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.\n */\n\n/**\n * @param {string} host\n * @returns {NormalizeIPv6Result}\n */\nfunction normalizeIPv6 (host) {\n  if (findToken(host, ':') < 2) { return { host, isIPV6: false } }\n  const ipv6 = getIPV6(host)\n\n  if (!ipv6.error) {\n    let newHost = ipv6.address\n    let escapedHost = ipv6.address\n    if (ipv6.zone) {\n      newHost += '%' + ipv6.zone\n      escapedHost += '%25' + ipv6.zone\n    }\n    return { host: newHost, isIPV6: true, escapedHost }\n  } else {\n    return { host, isIPV6: false }\n  }\n}\n\n/**\n * @param {string} str\n * @param {string} token\n * @returns {number}\n */\nfunction findToken (str, token) {\n  let ind = 0\n  for (let i = 0; i < str.length; i++) {\n    if (str[i] === token) ind++\n  }\n  return ind\n}\n\n/**\n * @param {string} path\n * @returns {string}\n *\n * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n */\nfunction removeDotSegments (path) {\n  let input = path\n  const output = []\n  let nextSlash = -1\n  let len = 0\n\n  // eslint-disable-next-line no-cond-assign\n  while (len = input.length) {\n    if (len === 1) {\n      if (input === '.') {\n        break\n      } else if (input === '/') {\n        output.push('/')\n        break\n      } else {\n        output.push(input)\n        break\n      }\n    } else if (len === 2) {\n      if (input[0] === '.') {\n        if (input[1] === '.') {\n          break\n        } else if (input[1] === '/') {\n          input = input.slice(2)\n          continue\n        }\n      } else if (input[0] === '/') {\n        if (input[1] === '.' || input[1] === '/') {\n          output.push('/')\n          break\n        }\n      }\n    } else if (len === 3) {\n      if (input === '/..') {\n        if (output.length !== 0) {\n          output.pop()\n        }\n        output.push('/')\n        break\n      }\n    }\n    if (input[0] === '.') {\n      if (input[1] === '.') {\n        if (input[2] === '/') {\n          input = input.slice(3)\n          continue\n        }\n      } else if (input[1] === '/') {\n        input = input.slice(2)\n        continue\n      }\n    } else if (input[0] === '/') {\n      if (input[1] === '.') {\n        if (input[2] === '/') {\n          input = input.slice(2)\n          continue\n        } else if (input[2] === '.') {\n          if (input[3] === '/') {\n            input = input.slice(3)\n            if (output.length !== 0) {\n              output.pop()\n            }\n            continue\n          }\n        }\n      }\n    }\n\n    // Rule 2E: Move normal path segment to output\n    if ((nextSlash = input.indexOf('/', 1)) === -1) {\n      output.push(input)\n      break\n    } else {\n      output.push(input.slice(0, nextSlash))\n      input = input.slice(nextSlash)\n    }\n  }\n\n  return output.join('')\n}\n\n/**\n * Re-escape RFC 3986 gen-delims that must not appear literally in the host.\n * After the URI regex parses, these characters cannot be literal in the host\n * field, so any that appear after decoding came from percent-encoding and\n * must be restored to prevent authority structure changes.\n *\n * @param {string} host\n * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping)\n * @returns {string}\n */\nconst HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' }\nconst HOST_DELIM_RE = /[@/?#:]/g\nconst HOST_DELIM_NO_COLON_RE = /[@/?#]/g\n\nfunction reescapeHostDelimiters (host, isIP) {\n  const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE\n  re.lastIndex = 0\n  return host.replace(re, (ch) => HOST_DELIMS[ch])\n}\n\n/**\n * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.\n * Reserved delimiters such as `%2F` and `%2E` stay escaped.\n *\n * @param {string} input\n * @param {boolean} [decodeUnreserved=false]\n * @returns {string}\n */\nfunction normalizePercentEncoding (input, decodeUnreserved = false) {\n  if (input.indexOf('%') === -1) {\n    return input\n  }\n\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    if (input[i] === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        const normalizedHex = hex.toUpperCase()\n        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n        if (decodeUnreserved && isUnreserved(decoded)) {\n          output += decoded\n        } else {\n          output += '%' + normalizedHex\n        }\n\n        i += 2\n        continue\n      }\n    }\n\n    output += input[i]\n  }\n\n  return output\n}\n\n/**\n * Normalizes path data without turning reserved escapes into live path syntax.\n * Valid escapes are uppercased, raw unsafe characters are escaped, and only\n * unreserved bytes that are not `.` are decoded.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction normalizePathEncoding (input) {\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    if (input[i] === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        const normalizedHex = hex.toUpperCase()\n        const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n        if (decoded !== '.' && isUnreserved(decoded)) {\n          output += decoded\n        } else {\n          output += '%' + normalizedHex\n        }\n\n        i += 2\n        continue\n      }\n    }\n\n    if (isPathCharacter(input[i])) {\n      output += input[i]\n    } else {\n      output += escape(input[i])\n    }\n  }\n\n  return output\n}\n\n/**\n * Escapes a component while preserving existing valid percent escapes.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction escapePreservingEscapes (input) {\n  let output = ''\n\n  for (let i = 0; i < input.length; i++) {\n    if (input[i] === '%' && i + 2 < input.length) {\n      const hex = input.slice(i + 1, i + 3)\n      if (isHexPair(hex)) {\n        output += '%' + hex.toUpperCase()\n        i += 2\n        continue\n      }\n    }\n\n    output += escape(input[i])\n  }\n\n  return output\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @returns {string|undefined}\n */\nfunction recomposeAuthority (component) {\n  const uriTokens = []\n\n  if (component.userinfo !== undefined) {\n    uriTokens.push(component.userinfo)\n    uriTokens.push('@')\n  }\n\n  if (component.host !== undefined) {\n    let host = unescape(component.host)\n    if (!isIPv4(host)) {\n      const ipV6res = normalizeIPv6(host)\n      if (ipV6res.isIPV6 === true) {\n        host = `[${ipV6res.escapedHost}]`\n      } else {\n        host = reescapeHostDelimiters(host, false)\n      }\n    }\n    uriTokens.push(host)\n  }\n\n  if (typeof component.port === 'number' || typeof component.port === 'string') {\n    uriTokens.push(':')\n    uriTokens.push(String(component.port))\n  }\n\n  return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n  nonSimpleDomain,\n  recomposeAuthority,\n  reescapeHostDelimiters,\n  normalizePercentEncoding,\n  normalizePathEncoding,\n  escapePreservingEscapes,\n  removeDotSegments,\n  isIPv4,\n  isUUID,\n  normalizeIPv6,\n  stringArrayToHexStripped\n}\n","'use strict'\n\nconst { isUUID } = require('./utils')\nconst URN_REG = /([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-.:;=@]|%[\\da-f]{2})+)/iu\n\nconst supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',\n  'wss', 'urn', 'urn:uuid'])\n\n/** @typedef {supportedSchemeNames[number]} SchemeName */\n\n/**\n * @param {string} name\n * @returns {name is SchemeName}\n */\nfunction isValidSchemeName (name) {\n  return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1\n}\n\n/**\n * @callback SchemeFn\n * @param {import('../types/index').URIComponent} component\n * @param {import('../types/index').Options} options\n * @returns {import('../types/index').URIComponent}\n */\n\n/**\n * @typedef {Object} SchemeHandler\n * @property {SchemeName} scheme - The scheme name.\n * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.\n * @property {SchemeFn} parse - Function to parse the URI component for this scheme.\n * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.\n * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.\n * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.\n * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.\n */\n\n/**\n * @param {import('../types/index').URIComponent} wsComponent\n * @returns {boolean}\n */\nfunction wsIsSecure (wsComponent) {\n  if (wsComponent.secure === true) {\n    return true\n  } else if (wsComponent.secure === false) {\n    return false\n  } else if (wsComponent.scheme) {\n    return (\n      wsComponent.scheme.length === 3 &&\n      (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&\n      (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&\n      (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')\n    )\n  } else {\n    return false\n  }\n}\n\n/** @type {SchemeFn} */\nfunction httpParse (component) {\n  if (!component.host) {\n    component.error = component.error || 'HTTP URIs must have a host.'\n  }\n\n  return component\n}\n\n/** @type {SchemeFn} */\nfunction httpSerialize (component) {\n  const secure = String(component.scheme).toLowerCase() === 'https'\n\n  // normalize the default port\n  if (component.port === (secure ? 443 : 80) || component.port === '') {\n    component.port = undefined\n  }\n\n  // normalize the empty path\n  if (!component.path) {\n    component.path = '/'\n  }\n\n  // NOTE: We do not parse query strings for HTTP URIs\n  // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n  // and not the HTTP spec.\n\n  return component\n}\n\n/** @type {SchemeFn} */\nfunction wsParse (wsComponent) {\n// indicate if the secure flag is set\n  wsComponent.secure = wsIsSecure(wsComponent)\n\n  // construct resouce name\n  wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')\n  wsComponent.path = undefined\n  wsComponent.query = undefined\n\n  return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction wsSerialize (wsComponent) {\n// normalize the default port\n  if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {\n    wsComponent.port = undefined\n  }\n\n  // ensure scheme matches secure flag\n  if (typeof wsComponent.secure === 'boolean') {\n    wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')\n    wsComponent.secure = undefined\n  }\n\n  // reconstruct path from resource name\n  if (wsComponent.resourceName) {\n    const [path, query] = wsComponent.resourceName.split('?')\n    wsComponent.path = (path && path !== '/' ? path : undefined)\n    wsComponent.query = query\n    wsComponent.resourceName = undefined\n  }\n\n  // forbid fragment component\n  wsComponent.fragment = undefined\n\n  return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnParse (urnComponent, options) {\n  if (!urnComponent.path) {\n    urnComponent.error = 'URN can not be parsed'\n    return urnComponent\n  }\n  const matches = urnComponent.path.match(URN_REG)\n  if (matches) {\n    const scheme = options.scheme || urnComponent.scheme || 'urn'\n    urnComponent.nid = matches[1].toLowerCase()\n    urnComponent.nss = matches[2]\n    const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`\n    const schemeHandler = getSchemeHandler(urnScheme)\n    urnComponent.path = undefined\n\n    if (schemeHandler) {\n      urnComponent = schemeHandler.parse(urnComponent, options)\n    }\n  } else {\n    urnComponent.error = urnComponent.error || 'URN can not be parsed.'\n  }\n\n  return urnComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnSerialize (urnComponent, options) {\n  if (urnComponent.nid === undefined) {\n    throw new Error('URN without nid cannot be serialized')\n  }\n  const scheme = options.scheme || urnComponent.scheme || 'urn'\n  const nid = urnComponent.nid.toLowerCase()\n  const urnScheme = `${scheme}:${options.nid || nid}`\n  const schemeHandler = getSchemeHandler(urnScheme)\n\n  if (schemeHandler) {\n    urnComponent = schemeHandler.serialize(urnComponent, options)\n  }\n\n  const uriComponent = urnComponent\n  const nss = urnComponent.nss\n  uriComponent.path = `${nid || options.nid}:${nss}`\n\n  options.skipEscape = true\n  return uriComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidParse (urnComponent, options) {\n  const uuidComponent = urnComponent\n  uuidComponent.uuid = uuidComponent.nss\n  uuidComponent.nss = undefined\n\n  if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {\n    uuidComponent.error = uuidComponent.error || 'UUID is not valid.'\n  }\n\n  return uuidComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidSerialize (uuidComponent) {\n  const urnComponent = uuidComponent\n  // normalize UUID\n  urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()\n  return urnComponent\n}\n\nconst http = /** @type {SchemeHandler} */ ({\n  scheme: 'http',\n  domainHost: true,\n  parse: httpParse,\n  serialize: httpSerialize\n})\n\nconst https = /** @type {SchemeHandler} */ ({\n  scheme: 'https',\n  domainHost: http.domainHost,\n  parse: httpParse,\n  serialize: httpSerialize\n})\n\nconst ws = /** @type {SchemeHandler} */ ({\n  scheme: 'ws',\n  domainHost: true,\n  parse: wsParse,\n  serialize: wsSerialize\n})\n\nconst wss = /** @type {SchemeHandler} */ ({\n  scheme: 'wss',\n  domainHost: ws.domainHost,\n  parse: ws.parse,\n  serialize: ws.serialize\n})\n\nconst urn = /** @type {SchemeHandler} */ ({\n  scheme: 'urn',\n  parse: urnParse,\n  serialize: urnSerialize,\n  skipNormalize: true\n})\n\nconst urnuuid = /** @type {SchemeHandler} */ ({\n  scheme: 'urn:uuid',\n  parse: urnuuidParse,\n  serialize: urnuuidSerialize,\n  skipNormalize: true\n})\n\nconst SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({\n  http,\n  https,\n  ws,\n  wss,\n  urn,\n  'urn:uuid': urnuuid\n})\n\nObject.setPrototypeOf(SCHEMES, null)\n\n/**\n * @param {string|undefined} scheme\n * @returns {SchemeHandler|undefined}\n */\nfunction getSchemeHandler (scheme) {\n  return (\n    scheme && (\n      SCHEMES[/** @type {SchemeName} */ (scheme)] ||\n      SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])\n  ) ||\n    undefined\n}\n\nmodule.exports = {\n  wsIsSecure,\n  SCHEMES,\n  isValidSchemeName,\n  getSchemeHandler,\n}\n","'use strict'\n\nconst { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils')\nconst { SCHEMES, getSchemeHandler } = require('./lib/schemes')\n\n/**\n * @template {import('./types/index').URIComponent|string} T\n * @param {T} uri\n * @param {import('./types/index').Options} [options]\n * @returns {T}\n */\nfunction normalize (uri, options) {\n  if (typeof uri === 'string') {\n    uri = /** @type {T} */ (normalizeString(uri, options))\n  } else if (typeof uri === 'object') {\n    uri = /** @type {T} */ (parse(serialize(uri, options), options))\n  }\n  return uri\n}\n\n/**\n * @param {string} baseURI\n * @param {string} relativeURI\n * @param {import('./types/index').Options} [options]\n * @returns {string}\n */\nfunction resolve (baseURI, relativeURI, options) {\n  const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }\n  const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)\n  schemelessOptions.skipEscape = true\n  return serialize(resolved, schemelessOptions)\n}\n\n/**\n * @param {import ('./types/index').URIComponent} base\n * @param {import ('./types/index').URIComponent} relative\n * @param {import('./types/index').Options} [options]\n * @param {boolean} [skipNormalization=false]\n * @returns {import ('./types/index').URIComponent}\n */\nfunction resolveComponent (base, relative, options, skipNormalization) {\n  /** @type {import('./types/index').URIComponent} */\n  const target = {}\n  if (!skipNormalization) {\n    base = parse(serialize(base, options), options) // normalize base component\n    relative = parse(serialize(relative, options), options) // normalize relative component\n  }\n  options = options || {}\n\n  if (!options.tolerant && relative.scheme) {\n    target.scheme = relative.scheme\n    // target.authority = relative.authority;\n    target.userinfo = relative.userinfo\n    target.host = relative.host\n    target.port = relative.port\n    target.path = removeDotSegments(relative.path || '')\n    target.query = relative.query\n  } else {\n    if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n      // target.authority = relative.authority;\n      target.userinfo = relative.userinfo\n      target.host = relative.host\n      target.port = relative.port\n      target.path = removeDotSegments(relative.path || '')\n      target.query = relative.query\n    } else {\n      if (!relative.path) {\n        target.path = base.path\n        if (relative.query !== undefined) {\n          target.query = relative.query\n        } else {\n          target.query = base.query\n        }\n      } else {\n        if (relative.path[0] === '/') {\n          target.path = removeDotSegments(relative.path)\n        } else {\n          if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n            target.path = '/' + relative.path\n          } else if (!base.path) {\n            target.path = relative.path\n          } else {\n            target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n          }\n          target.path = removeDotSegments(target.path)\n        }\n        target.query = relative.query\n      }\n      // target.authority = base.authority;\n      target.userinfo = base.userinfo\n      target.host = base.host\n      target.port = base.port\n    }\n    target.scheme = base.scheme\n  }\n\n  target.fragment = relative.fragment\n\n  return target\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uriA\n * @param {import ('./types/index').URIComponent|string} uriB\n * @param {import ('./types/index').Options} options\n * @returns {boolean}\n */\nfunction equal (uriA, uriB, options) {\n  const normalizedA = normalizeComparableURI(uriA, options)\n  const normalizedB = normalizeComparableURI(uriB, options)\n\n  return normalizedA !== undefined && normalizedB !== undefined && normalizedA.toLowerCase() === normalizedB.toLowerCase()\n}\n\n/**\n * @param {Readonly<import('./types/index').URIComponent>} cmpts\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction serialize (cmpts, opts) {\n  const component = {\n    host: cmpts.host,\n    scheme: cmpts.scheme,\n    userinfo: cmpts.userinfo,\n    port: cmpts.port,\n    path: cmpts.path,\n    query: cmpts.query,\n    nid: cmpts.nid,\n    nss: cmpts.nss,\n    uuid: cmpts.uuid,\n    fragment: cmpts.fragment,\n    reference: cmpts.reference,\n    resourceName: cmpts.resourceName,\n    secure: cmpts.secure,\n    error: ''\n  }\n  const options = Object.assign({}, opts)\n  const uriTokens = []\n\n  // find scheme handler\n  const schemeHandler = getSchemeHandler(options.scheme || component.scheme)\n\n  // perform scheme specific serialization\n  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)\n\n  if (component.path !== undefined) {\n    if (!options.skipEscape) {\n      component.path = escapePreservingEscapes(component.path)\n\n      if (component.scheme !== undefined) {\n        component.path = component.path.split('%3A').join(':')\n      }\n    } else {\n      component.path = normalizePercentEncoding(component.path)\n    }\n  }\n\n  if (options.reference !== 'suffix' && component.scheme) {\n    uriTokens.push(component.scheme, ':')\n  }\n\n  const authority = recomposeAuthority(component)\n  if (authority !== undefined) {\n    if (options.reference !== 'suffix') {\n      uriTokens.push('//')\n    }\n\n    uriTokens.push(authority)\n\n    if (component.path && component.path[0] !== '/') {\n      uriTokens.push('/')\n    }\n  }\n  if (component.path !== undefined) {\n    let s = component.path\n\n    if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n      s = removeDotSegments(s)\n    }\n\n    if (\n      authority === undefined &&\n      s[0] === '/' &&\n      s[1] === '/'\n    ) {\n      // don't allow the path to start with \"//\"\n      s = '/%2F' + s.slice(2)\n    }\n\n    uriTokens.push(s)\n  }\n\n  if (component.query !== undefined) {\n    uriTokens.push('?', component.query)\n  }\n\n  if (component.fragment !== undefined) {\n    uriTokens.push('#', component.fragment)\n  }\n  return uriTokens.join('')\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\n/**\n * @param {import('./types/index').URIComponent} parsed\n * @param {RegExpMatchArray} matches\n * @returns {string|undefined}\n */\nfunction getParseError (parsed, matches) {\n  if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {\n    return 'URI path must start with \"/\" when authority is present.'\n  }\n\n  if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {\n    return 'URI port is malformed.'\n  }\n\n  return undefined\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean }}\n */\nfunction parseWithStatus (uri, opts) {\n  const options = Object.assign({}, opts)\n  /** @type {import('./types/index').URIComponent} */\n  const parsed = {\n    scheme: undefined,\n    userinfo: undefined,\n    host: '',\n    port: undefined,\n    path: '',\n    query: undefined,\n    fragment: undefined\n  }\n\n  let malformedAuthorityOrPort = false\n\n  let isIP = false\n  if (options.reference === 'suffix') {\n    if (options.scheme) {\n      uri = options.scheme + ':' + uri\n    } else {\n      uri = '//' + uri\n    }\n  }\n\n  const matches = uri.match(URI_PARSE)\n\n  if (matches) {\n    // store each component\n    parsed.scheme = matches[1]\n    parsed.userinfo = matches[3]\n    parsed.host = matches[4]\n    parsed.port = parseInt(matches[5], 10)\n    parsed.path = matches[6] || ''\n    parsed.query = matches[7]\n    parsed.fragment = matches[8]\n\n    // fix port number\n    if (isNaN(parsed.port)) {\n      parsed.port = matches[5]\n    }\n\n    const parseError = getParseError(parsed, matches)\n    if (parseError !== undefined) {\n      parsed.error = parsed.error || parseError\n      malformedAuthorityOrPort = true\n    }\n\n    if (parsed.host) {\n      const ipv4result = isIPv4(parsed.host)\n      if (ipv4result === false) {\n        const ipv6result = normalizeIPv6(parsed.host)\n        parsed.host = ipv6result.host.toLowerCase()\n        isIP = ipv6result.isIPV6\n      } else {\n        isIP = true\n      }\n    }\n    if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n      parsed.reference = 'same-document'\n    } else if (parsed.scheme === undefined) {\n      parsed.reference = 'relative'\n    } else if (parsed.fragment === undefined) {\n      parsed.reference = 'absolute'\n    } else {\n      parsed.reference = 'uri'\n    }\n\n    // check for reference errors\n    if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n      parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n    }\n\n    // find scheme handler\n    const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)\n\n    // check if scheme can't handle IRIs\n    if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n      // if host component is a domain name\n      if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {\n        // convert Unicode IDN -> ASCII IDN\n        try {\n          parsed.host = URL.domainToASCII(parsed.host.toLowerCase())\n        } catch (e) {\n          parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n        }\n      }\n      // convert IRI -> URI\n    }\n\n    if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n      if (uri.indexOf('%') !== -1) {\n        if (parsed.scheme !== undefined) {\n          parsed.scheme = unescape(parsed.scheme)\n        }\n        if (parsed.host !== undefined) {\n          parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP)\n        }\n      }\n      if (parsed.path) {\n        parsed.path = normalizePathEncoding(parsed.path)\n      }\n      if (parsed.fragment) {\n        try {\n          parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))\n        } catch {\n          parsed.error = parsed.error || 'URI malformed'\n        }\n      }\n    }\n\n    // perform scheme specific parsing\n    if (schemeHandler && schemeHandler.parse) {\n      schemeHandler.parse(parsed, options)\n    }\n  } else {\n    parsed.error = parsed.error || 'URI can not be parsed.'\n  }\n  return { parsed, malformedAuthorityOrPort }\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns\n */\nfunction parse (uri, opts) {\n  return parseWithStatus(uri, opts).parsed\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction normalizeString (uri, opts) {\n  return normalizeStringWithStatus(uri, opts).normalized\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ normalized: string, malformedAuthorityOrPort: boolean }}\n */\nfunction normalizeStringWithStatus (uri, opts) {\n  const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts)\n  return {\n    normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),\n    malformedAuthorityOrPort\n  }\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string|undefined}\n */\nfunction normalizeComparableURI (uri, opts) {\n  if (typeof uri === 'string') {\n    const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts)\n    return malformedAuthorityOrPort ? undefined : normalized\n  }\n\n  if (typeof uri === 'object') {\n    return serialize(uri, opts)\n  }\n}\n\nconst fastUri = {\n  SCHEMES,\n  normalize,\n  resolve,\n  resolveComponent,\n  equal,\n  serialize,\n  parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst uri = require(\"fast-uri\");\nuri.code = 'require(\"ajv/dist/runtime/uri\").default';\nexports.default = uri;\n//# sourceMappingURL=uri.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nconst validation_error_1 = require(\"./runtime/validation_error\");\nconst ref_error_1 = require(\"./compile/ref_error\");\nconst rules_1 = require(\"./compile/rules\");\nconst compile_1 = require(\"./compile\");\nconst codegen_2 = require(\"./compile/codegen\");\nconst resolve_1 = require(\"./compile/resolve\");\nconst dataType_1 = require(\"./compile/validate/dataType\");\nconst util_1 = require(\"./compile/util\");\nconst $dataRefSchema = require(\"./refs/data.json\");\nconst uri_1 = require(\"./runtime/uri\");\nconst defaultRegExp = (str, flags) => new RegExp(str, flags);\ndefaultRegExp.code = \"new RegExp\";\nconst META_IGNORE_OPTIONS = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"];\nconst EXT_SCOPE_NAMES = new Set([\n    \"validate\",\n    \"serialize\",\n    \"parse\",\n    \"wrapper\",\n    \"root\",\n    \"schema\",\n    \"keyword\",\n    \"pattern\",\n    \"formats\",\n    \"validate$data\",\n    \"func\",\n    \"obj\",\n    \"Error\",\n]);\nconst removedOptions = {\n    errorDataPath: \"\",\n    format: \"`validateFormats: false` can be used instead.\",\n    nullable: '\"nullable\" keyword is supported by default.',\n    jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n    extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n    missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n    processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n    sourceCode: \"Use option `code: {source: true}`\",\n    strictDefaults: \"It is default now, see option `strict`.\",\n    strictKeywords: \"It is default now, see option `strict`.\",\n    uniqueItems: '\"uniqueItems\" keyword is always validated.',\n    unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n    cache: \"Map is used as cache, schema object as key.\",\n    serialize: \"Map is used as cache, schema object as key.\",\n    ajvErrors: \"It is default now.\",\n};\nconst deprecatedOptions = {\n    ignoreKeywordsWithRef: \"\",\n    jsPropertySyntax: \"\",\n    unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n};\nconst MAX_EXPRESSION = 200;\n// eslint-disable-next-line complexity\nfunction requiredOptions(o) {\n    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;\n    const s = o.strict;\n    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;\n    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;\n    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;\n    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;\n    return {\n        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,\n        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,\n        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : \"log\",\n        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : \"log\",\n        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,\n        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },\n        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,\n        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,\n        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,\n        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,\n        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,\n        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : \"$id\",\n        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,\n        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,\n        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,\n        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,\n        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,\n        uriResolver: uriResolver,\n    };\n}\nclass Ajv {\n    constructor(opts = {}) {\n        this.schemas = {};\n        this.refs = {};\n        this.formats = Object.create(null);\n        this._compilations = new Set();\n        this._loading = {};\n        this._cache = new Map();\n        opts = this.opts = { ...opts, ...requiredOptions(opts) };\n        const { es5, lines } = this.opts.code;\n        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });\n        this.logger = getLogger(opts.logger);\n        const formatOpt = opts.validateFormats;\n        opts.validateFormats = false;\n        this.RULES = (0, rules_1.getRules)();\n        checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\");\n        checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\");\n        this._metaOpts = getMetaSchemaOptions.call(this);\n        if (opts.formats)\n            addInitialFormats.call(this);\n        this._addVocabularies();\n        this._addDefaultMetaSchema();\n        if (opts.keywords)\n            addInitialKeywords.call(this, opts.keywords);\n        if (typeof opts.meta == \"object\")\n            this.addMetaSchema(opts.meta);\n        addInitialSchemas.call(this);\n        opts.validateFormats = formatOpt;\n    }\n    _addVocabularies() {\n        this.addKeyword(\"$async\");\n    }\n    _addDefaultMetaSchema() {\n        const { $data, meta, schemaId } = this.opts;\n        let _dataRefSchema = $dataRefSchema;\n        if (schemaId === \"id\") {\n            _dataRefSchema = { ...$dataRefSchema };\n            _dataRefSchema.id = _dataRefSchema.$id;\n            delete _dataRefSchema.$id;\n        }\n        if (meta && $data)\n            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);\n    }\n    defaultMeta() {\n        const { meta, schemaId } = this.opts;\n        return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined);\n    }\n    validate(schemaKeyRef, // key, ref or schema object\n    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n    data // to be validated\n    ) {\n        let v;\n        if (typeof schemaKeyRef == \"string\") {\n            v = this.getSchema(schemaKeyRef);\n            if (!v)\n                throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`);\n        }\n        else {\n            v = this.compile(schemaKeyRef);\n        }\n        const valid = v(data);\n        if (!(\"$async\" in v))\n            this.errors = v.errors;\n        return valid;\n    }\n    compile(schema, _meta) {\n        const sch = this._addSchema(schema, _meta);\n        return (sch.validate || this._compileSchemaEnv(sch));\n    }\n    compileAsync(schema, meta) {\n        if (typeof this.opts.loadSchema != \"function\") {\n            throw new Error(\"options.loadSchema should be a function\");\n        }\n        const { loadSchema } = this.opts;\n        return runCompileAsync.call(this, schema, meta);\n        async function runCompileAsync(_schema, _meta) {\n            await loadMetaSchema.call(this, _schema.$schema);\n            const sch = this._addSchema(_schema, _meta);\n            return sch.validate || _compileAsync.call(this, sch);\n        }\n        async function loadMetaSchema($ref) {\n            if ($ref && !this.getSchema($ref)) {\n                await runCompileAsync.call(this, { $ref }, true);\n            }\n        }\n        async function _compileAsync(sch) {\n            try {\n                return this._compileSchemaEnv(sch);\n            }\n            catch (e) {\n                if (!(e instanceof ref_error_1.default))\n                    throw e;\n                checkLoaded.call(this, e);\n                await loadMissingSchema.call(this, e.missingSchema);\n                return _compileAsync.call(this, sch);\n            }\n        }\n        function checkLoaded({ missingSchema: ref, missingRef }) {\n            if (this.refs[ref]) {\n                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);\n            }\n        }\n        async function loadMissingSchema(ref) {\n            const _schema = await _loadSchema.call(this, ref);\n            if (!this.refs[ref])\n                await loadMetaSchema.call(this, _schema.$schema);\n            if (!this.refs[ref])\n                this.addSchema(_schema, ref, meta);\n        }\n        async function _loadSchema(ref) {\n            const p = this._loading[ref];\n            if (p)\n                return p;\n            try {\n                return await (this._loading[ref] = loadSchema(ref));\n            }\n            finally {\n                delete this._loading[ref];\n            }\n        }\n    }\n    // Adds schema to the instance\n    addSchema(schema, // If array is passed, `key` will be ignored\n    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n    ) {\n        if (Array.isArray(schema)) {\n            for (const sch of schema)\n                this.addSchema(sch, undefined, _meta, _validateSchema);\n            return this;\n        }\n        let id;\n        if (typeof schema === \"object\") {\n            const { schemaId } = this.opts;\n            id = schema[schemaId];\n            if (id !== undefined && typeof id != \"string\") {\n                throw new Error(`schema ${schemaId} must be string`);\n            }\n        }\n        key = (0, resolve_1.normalizeId)(key || id);\n        this._checkUnique(key);\n        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);\n        return this;\n    }\n    // Add schema that will be used to validate other schemas\n    // options in META_IGNORE_OPTIONS are alway set to false\n    addMetaSchema(schema, key, // schema key\n    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n    ) {\n        this.addSchema(schema, key, true, _validateSchema);\n        return this;\n    }\n    //  Validate schema against its meta-schema\n    validateSchema(schema, throwOrLogError) {\n        if (typeof schema == \"boolean\")\n            return true;\n        let $schema;\n        $schema = schema.$schema;\n        if ($schema !== undefined && typeof $schema != \"string\") {\n            throw new Error(\"$schema must be a string\");\n        }\n        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();\n        if (!$schema) {\n            this.logger.warn(\"meta-schema not available\");\n            this.errors = null;\n            return true;\n        }\n        const valid = this.validate($schema, schema);\n        if (!valid && throwOrLogError) {\n            const message = \"schema is invalid: \" + this.errorsText();\n            if (this.opts.validateSchema === \"log\")\n                this.logger.error(message);\n            else\n                throw new Error(message);\n        }\n        return valid;\n    }\n    // Get compiled schema by `key` or `ref`.\n    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n    getSchema(keyRef) {\n        let sch;\n        while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\")\n            keyRef = sch;\n        if (sch === undefined) {\n            const { schemaId } = this.opts;\n            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });\n            sch = compile_1.resolveSchema.call(this, root, keyRef);\n            if (!sch)\n                return;\n            this.refs[keyRef] = sch;\n        }\n        return (sch.validate || this._compileSchemaEnv(sch));\n    }\n    // Remove cached schema(s).\n    // If no parameter is passed all schemas but meta-schemas are removed.\n    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n    removeSchema(schemaKeyRef) {\n        if (schemaKeyRef instanceof RegExp) {\n            this._removeAllSchemas(this.schemas, schemaKeyRef);\n            this._removeAllSchemas(this.refs, schemaKeyRef);\n            return this;\n        }\n        switch (typeof schemaKeyRef) {\n            case \"undefined\":\n                this._removeAllSchemas(this.schemas);\n                this._removeAllSchemas(this.refs);\n                this._cache.clear();\n                return this;\n            case \"string\": {\n                const sch = getSchEnv.call(this, schemaKeyRef);\n                if (typeof sch == \"object\")\n                    this._cache.delete(sch.schema);\n                delete this.schemas[schemaKeyRef];\n                delete this.refs[schemaKeyRef];\n                return this;\n            }\n            case \"object\": {\n                const cacheKey = schemaKeyRef;\n                this._cache.delete(cacheKey);\n                let id = schemaKeyRef[this.opts.schemaId];\n                if (id) {\n                    id = (0, resolve_1.normalizeId)(id);\n                    delete this.schemas[id];\n                    delete this.refs[id];\n                }\n                return this;\n            }\n            default:\n                throw new Error(\"ajv.removeSchema: invalid parameter\");\n        }\n    }\n    // add \"vocabulary\" - a collection of keywords\n    addVocabulary(definitions) {\n        for (const def of definitions)\n            this.addKeyword(def);\n        return this;\n    }\n    addKeyword(kwdOrDef, def // deprecated\n    ) {\n        let keyword;\n        if (typeof kwdOrDef == \"string\") {\n            keyword = kwdOrDef;\n            if (typeof def == \"object\") {\n                this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\");\n                def.keyword = keyword;\n            }\n        }\n        else if (typeof kwdOrDef == \"object\" && def === undefined) {\n            def = kwdOrDef;\n            keyword = def.keyword;\n            if (Array.isArray(keyword) && !keyword.length) {\n                throw new Error(\"addKeywords: keyword must be string or non-empty array\");\n            }\n        }\n        else {\n            throw new Error(\"invalid addKeywords parameters\");\n        }\n        checkKeyword.call(this, keyword, def);\n        if (!def) {\n            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));\n            return this;\n        }\n        keywordMetaschema.call(this, def);\n        const definition = {\n            ...def,\n            type: (0, dataType_1.getJSONTypes)(def.type),\n            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),\n        };\n        (0, util_1.eachItem)(keyword, definition.type.length === 0\n            ? (k) => addRule.call(this, k, definition)\n            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));\n        return this;\n    }\n    getKeyword(keyword) {\n        const rule = this.RULES.all[keyword];\n        return typeof rule == \"object\" ? rule.definition : !!rule;\n    }\n    // Remove keyword\n    removeKeyword(keyword) {\n        // TODO return type should be Ajv\n        const { RULES } = this;\n        delete RULES.keywords[keyword];\n        delete RULES.all[keyword];\n        for (const group of RULES.rules) {\n            const i = group.rules.findIndex((rule) => rule.keyword === keyword);\n            if (i >= 0)\n                group.rules.splice(i, 1);\n        }\n        return this;\n    }\n    // Add format\n    addFormat(name, format) {\n        if (typeof format == \"string\")\n            format = new RegExp(format);\n        this.formats[name] = format;\n        return this;\n    }\n    errorsText(errors = this.errors, // optional array of validation errors\n    { separator = \", \", dataVar = \"data\" } = {} // optional options with properties `separator` and `dataVar`\n    ) {\n        if (!errors || errors.length === 0)\n            return \"No errors\";\n        return errors\n            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n            .reduce((text, msg) => text + separator + msg);\n    }\n    $dataMetaSchema(metaSchema, keywordsJsonPointers) {\n        const rules = this.RULES.all;\n        metaSchema = JSON.parse(JSON.stringify(metaSchema));\n        for (const jsonPointer of keywordsJsonPointers) {\n            const segments = jsonPointer.split(\"/\").slice(1); // first segment is an empty string\n            let keywords = metaSchema;\n            for (const seg of segments)\n                keywords = keywords[seg];\n            for (const key in rules) {\n                const rule = rules[key];\n                if (typeof rule != \"object\")\n                    continue;\n                const { $data } = rule.definition;\n                const schema = keywords[key];\n                if ($data && schema)\n                    keywords[key] = schemaOrData(schema);\n            }\n        }\n        return metaSchema;\n    }\n    _removeAllSchemas(schemas, regex) {\n        for (const keyRef in schemas) {\n            const sch = schemas[keyRef];\n            if (!regex || regex.test(keyRef)) {\n                if (typeof sch == \"string\") {\n                    delete schemas[keyRef];\n                }\n                else if (sch && !sch.meta) {\n                    this._cache.delete(sch.schema);\n                    delete schemas[keyRef];\n                }\n            }\n        }\n    }\n    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {\n        let id;\n        const { schemaId } = this.opts;\n        if (typeof schema == \"object\") {\n            id = schema[schemaId];\n        }\n        else {\n            if (this.opts.jtd)\n                throw new Error(\"schema must be object\");\n            else if (typeof schema != \"boolean\")\n                throw new Error(\"schema must be object or boolean\");\n        }\n        let sch = this._cache.get(schema);\n        if (sch !== undefined)\n            return sch;\n        baseId = (0, resolve_1.normalizeId)(id || baseId);\n        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);\n        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });\n        this._cache.set(sch.schema, sch);\n        if (addSchema && !baseId.startsWith(\"#\")) {\n            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n            if (baseId)\n                this._checkUnique(baseId);\n            this.refs[baseId] = sch;\n        }\n        if (validateSchema)\n            this.validateSchema(schema, true);\n        return sch;\n    }\n    _checkUnique(id) {\n        if (this.schemas[id] || this.refs[id]) {\n            throw new Error(`schema with key or id \"${id}\" already exists`);\n        }\n    }\n    _compileSchemaEnv(sch) {\n        if (sch.meta)\n            this._compileMetaSchema(sch);\n        else\n            compile_1.compileSchema.call(this, sch);\n        /* istanbul ignore if */\n        if (!sch.validate)\n            throw new Error(\"ajv implementation error\");\n        return sch.validate;\n    }\n    _compileMetaSchema(sch) {\n        const currentOpts = this.opts;\n        this.opts = this._metaOpts;\n        try {\n            compile_1.compileSchema.call(this, sch);\n        }\n        finally {\n            this.opts = currentOpts;\n        }\n    }\n}\nAjv.ValidationError = validation_error_1.default;\nAjv.MissingRefError = ref_error_1.default;\nexports.default = Ajv;\nfunction checkOptions(checkOpts, options, msg, log = \"error\") {\n    for (const key in checkOpts) {\n        const opt = key;\n        if (opt in options)\n            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);\n    }\n}\nfunction getSchEnv(keyRef) {\n    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line\n    return this.schemas[keyRef] || this.refs[keyRef];\n}\nfunction addInitialSchemas() {\n    const optsSchemas = this.opts.schemas;\n    if (!optsSchemas)\n        return;\n    if (Array.isArray(optsSchemas))\n        this.addSchema(optsSchemas);\n    else\n        for (const key in optsSchemas)\n            this.addSchema(optsSchemas[key], key);\n}\nfunction addInitialFormats() {\n    for (const name in this.opts.formats) {\n        const format = this.opts.formats[name];\n        if (format)\n            this.addFormat(name, format);\n    }\n}\nfunction addInitialKeywords(defs) {\n    if (Array.isArray(defs)) {\n        this.addVocabulary(defs);\n        return;\n    }\n    this.logger.warn(\"keywords option as map is deprecated, pass array\");\n    for (const keyword in defs) {\n        const def = defs[keyword];\n        if (!def.keyword)\n            def.keyword = keyword;\n        this.addKeyword(def);\n    }\n}\nfunction getMetaSchemaOptions() {\n    const metaOpts = { ...this.opts };\n    for (const opt of META_IGNORE_OPTIONS)\n        delete metaOpts[opt];\n    return metaOpts;\n}\nconst noLogs = { log() { }, warn() { }, error() { } };\nfunction getLogger(logger) {\n    if (logger === false)\n        return noLogs;\n    if (logger === undefined)\n        return console;\n    if (logger.log && logger.warn && logger.error)\n        return logger;\n    throw new Error(\"logger must implement log, warn and error methods\");\n}\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;\nfunction checkKeyword(keyword, def) {\n    const { RULES } = this;\n    (0, util_1.eachItem)(keyword, (kwd) => {\n        if (RULES.keywords[kwd])\n            throw new Error(`Keyword ${kwd} is already defined`);\n        if (!KEYWORD_NAME.test(kwd))\n            throw new Error(`Keyword ${kwd} has invalid name`);\n    });\n    if (!def)\n        return;\n    if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n        throw new Error('$data keyword must have \"code\" or \"validate\" function');\n    }\n}\nfunction addRule(keyword, definition, dataType) {\n    var _a;\n    const post = definition === null || definition === void 0 ? void 0 : definition.post;\n    if (dataType && post)\n        throw new Error('keyword with \"post\" flag cannot have \"type\"');\n    const { RULES } = this;\n    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);\n    if (!ruleGroup) {\n        ruleGroup = { type: dataType, rules: [] };\n        RULES.rules.push(ruleGroup);\n    }\n    RULES.keywords[keyword] = true;\n    if (!definition)\n        return;\n    const rule = {\n        keyword,\n        definition: {\n            ...definition,\n            type: (0, dataType_1.getJSONTypes)(definition.type),\n            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),\n        },\n    };\n    if (definition.before)\n        addBeforeRule.call(this, ruleGroup, rule, definition.before);\n    else\n        ruleGroup.rules.push(rule);\n    RULES.all[keyword] = rule;\n    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));\n}\nfunction addBeforeRule(ruleGroup, rule, before) {\n    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);\n    if (i >= 0) {\n        ruleGroup.rules.splice(i, 0, rule);\n    }\n    else {\n        ruleGroup.rules.push(rule);\n        this.logger.warn(`rule ${before} is not defined`);\n    }\n}\nfunction keywordMetaschema(def) {\n    let { metaSchema } = def;\n    if (metaSchema === undefined)\n        return;\n    if (def.$data && this.opts.$data)\n        metaSchema = schemaOrData(metaSchema);\n    def.validateSchema = this.compile(metaSchema, true);\n}\nconst $dataRef = {\n    $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n};\nfunction schemaOrData(schema) {\n    return { anyOf: [schema, $dataRef] };\n}\n//# sourceMappingURL=core.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst def = {\n    keyword: \"id\",\n    code() {\n        throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID');\n    },\n};\nexports.default = def;\n//# sourceMappingURL=id.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.callRef = exports.getValidate = void 0;\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst compile_1 = require(\"../../compile\");\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"$ref\",\n    schemaType: \"string\",\n    code(cxt) {\n        const { gen, schema: $ref, it } = cxt;\n        const { baseId, schemaEnv: env, validateName, opts, self } = it;\n        const { root } = env;\n        if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId)\n            return callRootRef();\n        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);\n        if (schOrEnv === undefined)\n            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);\n        if (schOrEnv instanceof compile_1.SchemaEnv)\n            return callValidate(schOrEnv);\n        return inlineRefSchema(schOrEnv);\n        function callRootRef() {\n            if (env === root)\n                return callRef(cxt, validateName, env, env.$async);\n            const rootName = gen.scopeValue(\"root\", { ref: root });\n            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);\n        }\n        function callValidate(sch) {\n            const v = getValidate(cxt, sch);\n            callRef(cxt, v, sch, sch.$async);\n        }\n        function inlineRefSchema(sch) {\n            const schName = gen.scopeValue(\"schema\", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });\n            const valid = gen.name(\"valid\");\n            const schCxt = cxt.subschema({\n                schema: sch,\n                dataTypes: [],\n                schemaPath: codegen_1.nil,\n                topSchemaRef: schName,\n                errSchemaPath: $ref,\n            }, valid);\n            cxt.mergeEvaluated(schCxt);\n            cxt.ok(valid);\n        }\n    },\n};\nfunction getValidate(cxt, sch) {\n    const { gen } = cxt;\n    return sch.validate\n        ? gen.scopeValue(\"validate\", { ref: sch.validate })\n        : (0, codegen_1._) `${gen.scopeValue(\"wrapper\", { ref: sch })}.validate`;\n}\nexports.getValidate = getValidate;\nfunction callRef(cxt, v, sch, $async) {\n    const { gen, it } = cxt;\n    const { allErrors, schemaEnv: env, opts } = it;\n    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;\n    if ($async)\n        callAsyncRef();\n    else\n        callSyncRef();\n    function callAsyncRef() {\n        if (!env.$async)\n            throw new Error(\"async schema referenced by sync schema\");\n        const valid = gen.let(\"valid\");\n        gen.try(() => {\n            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);\n            addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result\n            if (!allErrors)\n                gen.assign(valid, true);\n        }, (e) => {\n            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));\n            addErrorsFrom(e);\n            if (!allErrors)\n                gen.assign(valid, false);\n        });\n        cxt.ok(valid);\n    }\n    function callSyncRef() {\n        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));\n    }\n    function addErrorsFrom(source) {\n        const errs = (0, codegen_1._) `${source}.errors`;\n        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged\n        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n    }\n    function addEvaluatedFrom(source) {\n        var _a;\n        if (!it.opts.unevaluated)\n            return;\n        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;\n        // TODO refactor\n        if (it.props !== true) {\n            if (schEvaluated && !schEvaluated.dynamicProps) {\n                if (schEvaluated.props !== undefined) {\n                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);\n                }\n            }\n            else {\n                const props = gen.var(\"props\", (0, codegen_1._) `${source}.evaluated.props`);\n                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);\n            }\n        }\n        if (it.items !== true) {\n            if (schEvaluated && !schEvaluated.dynamicItems) {\n                if (schEvaluated.items !== undefined) {\n                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);\n                }\n            }\n            else {\n                const items = gen.var(\"items\", (0, codegen_1._) `${source}.evaluated.items`);\n                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);\n            }\n        }\n    }\n}\nexports.callRef = callRef;\nexports.default = def;\n//# sourceMappingURL=ref.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst id_1 = require(\"./id\");\nconst ref_1 = require(\"./ref\");\nconst core = [\n    \"$schema\",\n    \"$id\",\n    \"$defs\",\n    \"$vocabulary\",\n    { keyword: \"$comment\" },\n    \"definitions\",\n    id_1.default,\n    ref_1.default,\n];\nexports.default = core;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n    maximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n    minimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n    exclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n    exclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,\n    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: Object.keys(KWDs),\n    type: \"number\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode } = cxt;\n        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitNumber.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,\n    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"multipleOf\",\n    type: \"number\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, schemaCode, it } = cxt;\n        // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n        const prec = it.opts.multipleOfPrecision;\n        const res = gen.let(\"res\");\n        const invalid = prec\n            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n            : (0, codegen_1._) `${res} !== parseInt(${res})`;\n        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=multipleOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nfunction ucs2length(str) {\n    const len = str.length;\n    let length = 0;\n    let pos = 0;\n    let value;\n    while (pos < len) {\n        length++;\n        value = str.charCodeAt(pos++);\n        if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n            // high surrogate, and there is a next character\n            value = str.charCodeAt(pos);\n            if ((value & 0xfc00) === 0xdc00)\n                pos++; // low surrogate\n        }\n    }\n    return length;\n}\nexports.default = ucs2length;\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default';\n//# sourceMappingURL=ucs2length.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst ucs2length_1 = require(\"../../runtime/ucs2length\");\nconst error = {\n    message({ keyword, schemaCode }) {\n        const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\";\n        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;\n    },\n    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: [\"maxLength\", \"minLength\"],\n    type: \"string\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode, it } = cxt;\n        const op = keyword === \"maxLength\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;\n        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitLength.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern \"${schemaCode}\"`,\n    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"pattern\",\n    type: \"string\",\n    schemaType: \"string\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schema, schemaCode, it } = cxt;\n        const u = it.opts.unicodeRegExp ? \"u\" : \"\";\n        if ($data) {\n            const { regExp } = it.opts.code;\n            const regExpCode = regExp.code === \"new RegExp\" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);\n            const valid = gen.let(\"valid\");\n            gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));\n            cxt.fail$data((0, codegen_1._) `!${valid}`);\n        }\n        else {\n            const regExp = (0, code_1.usePattern)(cxt, schema);\n            cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=pattern.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message({ keyword, schemaCode }) {\n        const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\";\n        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;\n    },\n    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: [\"maxProperties\", \"minProperties\"],\n    type: \"object\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode } = cxt;\n        const op = keyword === \"maxProperties\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,\n    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,\n};\nconst def = {\n    keyword: \"required\",\n    type: \"object\",\n    schemaType: \"array\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, schema, schemaCode, data, $data, it } = cxt;\n        const { opts } = it;\n        if (!$data && schema.length === 0)\n            return;\n        const useLoop = schema.length >= opts.loopRequired;\n        if (it.allErrors)\n            allErrorsMode();\n        else\n            exitOnErrorMode();\n        if (opts.strictRequired) {\n            const props = cxt.parentSchema.properties;\n            const { definedProperties } = cxt.it;\n            for (const requiredKey of schema) {\n                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {\n                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n                    const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`;\n                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);\n                }\n            }\n        }\n        function allErrorsMode() {\n            if (useLoop || $data) {\n                cxt.block$data(codegen_1.nil, loopAllRequired);\n            }\n            else {\n                for (const prop of schema) {\n                    (0, code_1.checkReportMissingProp)(cxt, prop);\n                }\n            }\n        }\n        function exitOnErrorMode() {\n            const missing = gen.let(\"missing\");\n            if (useLoop || $data) {\n                const valid = gen.let(\"valid\", true);\n                cxt.block$data(valid, () => loopUntilMissing(missing, valid));\n                cxt.ok(valid);\n            }\n            else {\n                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));\n                (0, code_1.reportMissingProp)(cxt, missing);\n                gen.else();\n            }\n        }\n        function loopAllRequired() {\n            gen.forOf(\"prop\", schemaCode, (prop) => {\n                cxt.setParams({ missingProperty: prop });\n                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());\n            });\n        }\n        function loopUntilMissing(missing, valid) {\n            cxt.setParams({ missingProperty: missing });\n            gen.forOf(missing, schemaCode, () => {\n                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));\n                gen.if((0, codegen_1.not)(valid), () => {\n                    cxt.error();\n                    gen.break();\n                });\n            }, codegen_1.nil);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=required.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message({ keyword, schemaCode }) {\n        const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\";\n        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;\n    },\n    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n    keyword: [\"maxItems\", \"minItems\"],\n    type: \"array\",\n    schemaType: \"number\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { keyword, data, schemaCode } = cxt;\n        const op = keyword === \"maxItems\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=limitItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://github.com/ajv-validator/ajv/issues/889\nconst equal = require(\"fast-deep-equal\");\nequal.code = 'require(\"ajv/dist/runtime/equal\").default';\nexports.default = equal;\n//# sourceMappingURL=equal.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dataType_1 = require(\"../../compile/validate/dataType\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,\n};\nconst def = {\n    keyword: \"uniqueItems\",\n    type: \"array\",\n    schemaType: \"boolean\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;\n        if (!$data && !schema)\n            return;\n        const valid = gen.let(\"valid\");\n        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];\n        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);\n        cxt.ok(valid);\n        function validateUniqueItems() {\n            const i = gen.let(\"i\", (0, codegen_1._) `${data}.length`);\n            const j = gen.let(\"j\");\n            cxt.setParams({ i, j });\n            gen.assign(valid, true);\n            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));\n        }\n        function canOptimize() {\n            return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\");\n        }\n        function loopN(i, j) {\n            const item = gen.name(\"item\");\n            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);\n            const indices = gen.const(\"indices\", (0, codegen_1._) `{}`);\n            gen.for((0, codegen_1._) `;${i}--;`, () => {\n                gen.let(item, (0, codegen_1._) `${data}[${i}]`);\n                gen.if(wrongType, (0, codegen_1._) `continue`);\n                if (itemTypes.length > 1)\n                    gen.if((0, codegen_1._) `typeof ${item} == \"string\"`, (0, codegen_1._) `${item} += \"_\"`);\n                gen\n                    .if((0, codegen_1._) `typeof ${indices}[${item}] == \"number\"`, () => {\n                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);\n                    cxt.error();\n                    gen.assign(valid, false).break();\n                })\n                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);\n            });\n        }\n        function loopN2(i, j) {\n            const eql = (0, util_1.useFunc)(gen, equal_1.default);\n            const outer = gen.name(\"outer\");\n            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {\n                cxt.error();\n                gen.assign(valid, false).break(outer);\n            })));\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=uniqueItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n    message: \"must be equal to constant\",\n    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"const\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schemaCode, schema } = cxt;\n        if ($data || (schema && typeof schema == \"object\")) {\n            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);\n        }\n        else {\n            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=const.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n    message: \"must be equal to one of the allowed values\",\n    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"enum\",\n    schemaType: \"array\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, $data, schema, schemaCode, it } = cxt;\n        if (!$data && schema.length === 0)\n            throw new Error(\"enum must have non-empty array\");\n        const useLoop = schema.length >= it.opts.loopEnum;\n        let eql;\n        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));\n        let valid;\n        if (useLoop || $data) {\n            valid = gen.let(\"valid\");\n            cxt.block$data(valid, loopEnum);\n        }\n        else {\n            /* istanbul ignore if */\n            if (!Array.isArray(schema))\n                throw new Error(\"ajv implementation error\");\n            const vSchema = gen.const(\"vSchema\", schemaCode);\n            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));\n        }\n        cxt.pass(valid);\n        function loopEnum() {\n            gen.assign(valid, false);\n            gen.forOf(\"v\", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));\n        }\n        function equalCode(vSchema, i) {\n            const sch = schema[i];\n            return typeof sch === \"object\" && sch !== null\n                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`\n                : (0, codegen_1._) `${data} === ${sch}`;\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=enum.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst limitNumber_1 = require(\"./limitNumber\");\nconst multipleOf_1 = require(\"./multipleOf\");\nconst limitLength_1 = require(\"./limitLength\");\nconst pattern_1 = require(\"./pattern\");\nconst limitProperties_1 = require(\"./limitProperties\");\nconst required_1 = require(\"./required\");\nconst limitItems_1 = require(\"./limitItems\");\nconst uniqueItems_1 = require(\"./uniqueItems\");\nconst const_1 = require(\"./const\");\nconst enum_1 = require(\"./enum\");\nconst validation = [\n    // number\n    limitNumber_1.default,\n    multipleOf_1.default,\n    // string\n    limitLength_1.default,\n    pattern_1.default,\n    // object\n    limitProperties_1.default,\n    required_1.default,\n    // array\n    limitItems_1.default,\n    uniqueItems_1.default,\n    // any\n    { keyword: \"type\", schemaType: [\"string\", \"array\"] },\n    { keyword: \"nullable\", schemaType: \"boolean\" },\n    const_1.default,\n    enum_1.default,\n];\nexports.default = validation;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateAdditionalItems = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n    keyword: \"additionalItems\",\n    type: \"array\",\n    schemaType: [\"boolean\", \"object\"],\n    before: \"uniqueItems\",\n    error,\n    code(cxt) {\n        const { parentSchema, it } = cxt;\n        const { items } = parentSchema;\n        if (!Array.isArray(items)) {\n            (0, util_1.checkStrictMode)(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas');\n            return;\n        }\n        validateAdditionalItems(cxt, items);\n    },\n};\nfunction validateAdditionalItems(cxt, items) {\n    const { gen, schema, data, keyword, it } = cxt;\n    it.items = true;\n    const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n    if (schema === false) {\n        cxt.setParams({ len: items.length });\n        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);\n    }\n    else if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n        const valid = gen.var(\"valid\", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var\n        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));\n        cxt.ok(valid);\n    }\n    function validateItems(valid) {\n        gen.forRange(\"i\", items.length, len, (i) => {\n            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);\n            if (!it.allErrors)\n                gen.if((0, codegen_1.not)(valid), () => gen.break());\n        });\n    }\n}\nexports.validateAdditionalItems = validateAdditionalItems;\nexports.default = def;\n//# sourceMappingURL=additionalItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateTuple = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst def = {\n    keyword: \"items\",\n    type: \"array\",\n    schemaType: [\"object\", \"array\", \"boolean\"],\n    before: \"uniqueItems\",\n    code(cxt) {\n        const { schema, it } = cxt;\n        if (Array.isArray(schema))\n            return validateTuple(cxt, \"additionalItems\", schema);\n        it.items = true;\n        if ((0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        cxt.ok((0, code_1.validateArray)(cxt));\n    },\n};\nfunction validateTuple(cxt, extraItems, schArr = cxt.schema) {\n    const { gen, parentSchema, data, keyword, it } = cxt;\n    checkStrictTuple(parentSchema);\n    if (it.opts.unevaluated && schArr.length && it.items !== true) {\n        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);\n    }\n    const valid = gen.name(\"valid\");\n    const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n    schArr.forEach((sch, i) => {\n        if ((0, util_1.alwaysValidSchema)(it, sch))\n            return;\n        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({\n            keyword,\n            schemaProp: i,\n            dataProp: i,\n        }, valid));\n        cxt.ok(valid);\n    });\n    function checkStrictTuple(sch) {\n        const { opts, errSchemaPath } = it;\n        const l = schArr.length;\n        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);\n        if (opts.strictTuples && !fullTuple) {\n            const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`;\n            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);\n        }\n    }\n}\nexports.validateTuple = validateTuple;\nexports.default = def;\n//# sourceMappingURL=items.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst items_1 = require(\"./items\");\nconst def = {\n    keyword: \"prefixItems\",\n    type: \"array\",\n    schemaType: [\"array\"],\n    before: \"uniqueItems\",\n    code: (cxt) => (0, items_1.validateTuple)(cxt, \"items\"),\n};\nexports.default = def;\n//# sourceMappingURL=prefixItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst additionalItems_1 = require(\"./additionalItems\");\nconst error = {\n    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n    keyword: \"items\",\n    type: \"array\",\n    schemaType: [\"object\", \"boolean\"],\n    before: \"uniqueItems\",\n    error,\n    code(cxt) {\n        const { schema, parentSchema, it } = cxt;\n        const { prefixItems } = parentSchema;\n        it.items = true;\n        if ((0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        if (prefixItems)\n            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);\n        else\n            cxt.ok((0, code_1.validateArray)(cxt));\n    },\n};\nexports.default = def;\n//# sourceMappingURL=items2020.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { min, max } }) => max === undefined\n        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`\n        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,\n    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,\n};\nconst def = {\n    keyword: \"contains\",\n    type: \"array\",\n    schemaType: [\"object\", \"boolean\"],\n    before: \"uniqueItems\",\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, schema, parentSchema, data, it } = cxt;\n        let min;\n        let max;\n        const { minContains, maxContains } = parentSchema;\n        if (it.opts.next) {\n            min = minContains === undefined ? 1 : minContains;\n            max = maxContains;\n        }\n        else {\n            min = 1;\n        }\n        const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n        cxt.setParams({ min, max });\n        if (max === undefined && min === 0) {\n            (0, util_1.checkStrictMode)(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`);\n            return;\n        }\n        if (max !== undefined && min > max) {\n            (0, util_1.checkStrictMode)(it, `\"minContains\" > \"maxContains\" is always invalid`);\n            cxt.fail();\n            return;\n        }\n        if ((0, util_1.alwaysValidSchema)(it, schema)) {\n            let cond = (0, codegen_1._) `${len} >= ${min}`;\n            if (max !== undefined)\n                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;\n            cxt.pass(cond);\n            return;\n        }\n        it.items = true;\n        const valid = gen.name(\"valid\");\n        if (max === undefined && min === 1) {\n            validateItems(valid, () => gen.if(valid, () => gen.break()));\n        }\n        else if (min === 0) {\n            gen.let(valid, true);\n            if (max !== undefined)\n                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);\n        }\n        else {\n            gen.let(valid, false);\n            validateItemsWithCount();\n        }\n        cxt.result(valid, () => cxt.reset());\n        function validateItemsWithCount() {\n            const schValid = gen.name(\"_valid\");\n            const count = gen.let(\"count\", 0);\n            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));\n        }\n        function validateItems(_valid, block) {\n            gen.forRange(\"i\", 0, len, (i) => {\n                cxt.subschema({\n                    keyword: \"contains\",\n                    dataProp: i,\n                    dataPropType: util_1.Type.Num,\n                    compositeRule: true,\n                }, _valid);\n                block();\n            });\n        }\n        function checkLimits(count) {\n            gen.code((0, codegen_1._) `${count}++`);\n            if (max === undefined) {\n                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());\n            }\n            else {\n                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());\n                if (min === 1)\n                    gen.assign(valid, true);\n                else\n                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));\n            }\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=contains.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nexports.error = {\n    message: ({ params: { property, depsCount, deps } }) => {\n        const property_ies = depsCount === 1 ? \"property\" : \"properties\";\n        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;\n    },\n    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},\n    missingProperty: ${missingProperty},\n    depsCount: ${depsCount},\n    deps: ${deps}}`, // TODO change to reference\n};\nconst def = {\n    keyword: \"dependencies\",\n    type: \"object\",\n    schemaType: \"object\",\n    error: exports.error,\n    code(cxt) {\n        const [propDeps, schDeps] = splitDependencies(cxt);\n        validatePropertyDeps(cxt, propDeps);\n        validateSchemaDeps(cxt, schDeps);\n    },\n};\nfunction splitDependencies({ schema }) {\n    const propertyDeps = {};\n    const schemaDeps = {};\n    for (const key in schema) {\n        if (key === \"__proto__\")\n            continue;\n        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;\n        deps[key] = schema[key];\n    }\n    return [propertyDeps, schemaDeps];\n}\nfunction validatePropertyDeps(cxt, propertyDeps = cxt.schema) {\n    const { gen, data, it } = cxt;\n    if (Object.keys(propertyDeps).length === 0)\n        return;\n    const missing = gen.let(\"missing\");\n    for (const prop in propertyDeps) {\n        const deps = propertyDeps[prop];\n        if (deps.length === 0)\n            continue;\n        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);\n        cxt.setParams({\n            property: prop,\n            depsCount: deps.length,\n            deps: deps.join(\", \"),\n        });\n        if (it.allErrors) {\n            gen.if(hasProperty, () => {\n                for (const depProp of deps) {\n                    (0, code_1.checkReportMissingProp)(cxt, depProp);\n                }\n            });\n        }\n        else {\n            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);\n            (0, code_1.reportMissingProp)(cxt, missing);\n            gen.else();\n        }\n    }\n}\nexports.validatePropertyDeps = validatePropertyDeps;\nfunction validateSchemaDeps(cxt, schemaDeps = cxt.schema) {\n    const { gen, data, keyword, it } = cxt;\n    const valid = gen.name(\"valid\");\n    for (const prop in schemaDeps) {\n        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))\n            continue;\n        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {\n            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);\n            cxt.mergeValidEvaluated(schCxt, valid);\n        }, () => gen.var(valid, true) // TODO var\n        );\n        cxt.ok(valid);\n    }\n}\nexports.validateSchemaDeps = validateSchemaDeps;\nexports.default = def;\n//# sourceMappingURL=dependencies.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: \"property name must be valid\",\n    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,\n};\nconst def = {\n    keyword: \"propertyNames\",\n    type: \"object\",\n    schemaType: [\"object\", \"boolean\"],\n    error,\n    code(cxt) {\n        const { gen, schema, data, it } = cxt;\n        if ((0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        const valid = gen.name(\"valid\");\n        gen.forIn(\"key\", data, (key) => {\n            cxt.setParams({ propertyName: key });\n            cxt.subschema({\n                keyword: \"propertyNames\",\n                data: key,\n                dataTypes: [\"string\"],\n                propertyName: key,\n                compositeRule: true,\n            }, valid);\n            gen.if((0, codegen_1.not)(valid), () => {\n                cxt.error(true);\n                if (!it.allErrors)\n                    gen.break();\n            });\n        });\n        cxt.ok(valid);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=propertyNames.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: \"must NOT have additional properties\",\n    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,\n};\nconst def = {\n    keyword: \"additionalProperties\",\n    type: [\"object\"],\n    schemaType: [\"boolean\", \"object\"],\n    allowUndefined: true,\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, schema, parentSchema, data, errsCount, it } = cxt;\n        /* istanbul ignore if */\n        if (!errsCount)\n            throw new Error(\"ajv implementation error\");\n        const { allErrors, opts } = it;\n        it.props = true;\n        if (opts.removeAdditional !== \"all\" && (0, util_1.alwaysValidSchema)(it, schema))\n            return;\n        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);\n        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);\n        checkAdditionalProperties();\n        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n        function checkAdditionalProperties() {\n            gen.forIn(\"key\", data, (key) => {\n                if (!props.length && !patProps.length)\n                    additionalPropertyCode(key);\n                else\n                    gen.if(isAdditional(key), () => additionalPropertyCode(key));\n            });\n        }\n        function isAdditional(key) {\n            let definedProp;\n            if (props.length > 8) {\n                // TODO maybe an option instead of hard-coded 8?\n                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, \"properties\");\n                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);\n            }\n            else if (props.length) {\n                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));\n            }\n            else {\n                definedProp = codegen_1.nil;\n            }\n            if (patProps.length) {\n                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));\n            }\n            return (0, codegen_1.not)(definedProp);\n        }\n        function deleteAdditional(key) {\n            gen.code((0, codegen_1._) `delete ${data}[${key}]`);\n        }\n        function additionalPropertyCode(key) {\n            if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n                deleteAdditional(key);\n                return;\n            }\n            if (schema === false) {\n                cxt.setParams({ additionalProperty: key });\n                cxt.error();\n                if (!allErrors)\n                    gen.break();\n                return;\n            }\n            if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n                const valid = gen.name(\"valid\");\n                if (opts.removeAdditional === \"failing\") {\n                    applyAdditionalSchema(key, valid, false);\n                    gen.if((0, codegen_1.not)(valid), () => {\n                        cxt.reset();\n                        deleteAdditional(key);\n                    });\n                }\n                else {\n                    applyAdditionalSchema(key, valid);\n                    if (!allErrors)\n                        gen.if((0, codegen_1.not)(valid), () => gen.break());\n                }\n            }\n        }\n        function applyAdditionalSchema(key, valid, errors) {\n            const subschema = {\n                keyword: \"additionalProperties\",\n                dataProp: key,\n                dataPropType: util_1.Type.Str,\n            };\n            if (errors === false) {\n                Object.assign(subschema, {\n                    compositeRule: true,\n                    createErrors: false,\n                    allErrors: false,\n                });\n            }\n            cxt.subschema(subschema, valid);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=additionalProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst validate_1 = require(\"../../compile/validate\");\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst def = {\n    keyword: \"properties\",\n    type: \"object\",\n    schemaType: \"object\",\n    code(cxt) {\n        const { gen, schema, parentSchema, data, it } = cxt;\n        if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, \"additionalProperties\"));\n        }\n        const allProps = (0, code_1.allSchemaProperties)(schema);\n        for (const prop of allProps) {\n            it.definedProperties.add(prop);\n        }\n        if (it.opts.unevaluated && allProps.length && it.props !== true) {\n            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);\n        }\n        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));\n        if (properties.length === 0)\n            return;\n        const valid = gen.name(\"valid\");\n        for (const prop of properties) {\n            if (hasDefault(prop)) {\n                applyPropertySchema(prop);\n            }\n            else {\n                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));\n                applyPropertySchema(prop);\n                if (!it.allErrors)\n                    gen.else().var(valid, true);\n                gen.endIf();\n            }\n            cxt.it.definedProperties.add(prop);\n            cxt.ok(valid);\n        }\n        function hasDefault(prop) {\n            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;\n        }\n        function applyPropertySchema(prop) {\n            cxt.subschema({\n                keyword: \"properties\",\n                schemaProp: prop,\n                dataProp: prop,\n            }, valid);\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=properties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst util_2 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"patternProperties\",\n    type: \"object\",\n    schemaType: \"object\",\n    code(cxt) {\n        const { gen, schema, data, parentSchema, it } = cxt;\n        const { opts } = it;\n        const patterns = (0, code_1.allSchemaProperties)(schema);\n        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));\n        if (patterns.length === 0 ||\n            (alwaysValidPatterns.length === patterns.length &&\n                (!it.opts.unevaluated || it.props === true))) {\n            return;\n        }\n        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;\n        const valid = gen.name(\"valid\");\n        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {\n            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);\n        }\n        const { props } = it;\n        validatePatternProperties();\n        function validatePatternProperties() {\n            for (const pat of patterns) {\n                if (checkProperties)\n                    checkMatchingProperties(pat);\n                if (it.allErrors) {\n                    validateProperties(pat);\n                }\n                else {\n                    gen.var(valid, true); // TODO var\n                    validateProperties(pat);\n                    gen.if(valid);\n                }\n            }\n        }\n        function checkMatchingProperties(pat) {\n            for (const prop in checkProperties) {\n                if (new RegExp(pat).test(prop)) {\n                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);\n                }\n            }\n        }\n        function validateProperties(pat) {\n            gen.forIn(\"key\", data, (key) => {\n                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {\n                    const alwaysValid = alwaysValidPatterns.includes(pat);\n                    if (!alwaysValid) {\n                        cxt.subschema({\n                            keyword: \"patternProperties\",\n                            schemaProp: pat,\n                            dataProp: key,\n                            dataPropType: util_2.Type.Str,\n                        }, valid);\n                    }\n                    if (it.opts.unevaluated && props !== true) {\n                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);\n                    }\n                    else if (!alwaysValid && !it.allErrors) {\n                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n                        // or if all properties were evaluated (props === true)\n                        gen.if((0, codegen_1.not)(valid), () => gen.break());\n                    }\n                });\n            });\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=patternProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"not\",\n    schemaType: [\"object\", \"boolean\"],\n    trackErrors: true,\n    code(cxt) {\n        const { gen, schema, it } = cxt;\n        if ((0, util_1.alwaysValidSchema)(it, schema)) {\n            cxt.fail();\n            return;\n        }\n        const valid = gen.name(\"valid\");\n        cxt.subschema({\n            keyword: \"not\",\n            compositeRule: true,\n            createErrors: false,\n            allErrors: false,\n        }, valid);\n        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());\n    },\n    error: { message: \"must NOT be valid\" },\n};\nexports.default = def;\n//# sourceMappingURL=not.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst def = {\n    keyword: \"anyOf\",\n    schemaType: \"array\",\n    trackErrors: true,\n    code: code_1.validateUnion,\n    error: { message: \"must match a schema in anyOf\" },\n};\nexports.default = def;\n//# sourceMappingURL=anyOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: \"must match exactly one schema in oneOf\",\n    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,\n};\nconst def = {\n    keyword: \"oneOf\",\n    schemaType: \"array\",\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, schema, parentSchema, it } = cxt;\n        /* istanbul ignore if */\n        if (!Array.isArray(schema))\n            throw new Error(\"ajv implementation error\");\n        if (it.opts.discriminator && parentSchema.discriminator)\n            return;\n        const schArr = schema;\n        const valid = gen.let(\"valid\", false);\n        const passing = gen.let(\"passing\", null);\n        const schValid = gen.name(\"_valid\");\n        cxt.setParams({ passing });\n        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n        gen.block(validateOneOf);\n        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n        function validateOneOf() {\n            schArr.forEach((sch, i) => {\n                let schCxt;\n                if ((0, util_1.alwaysValidSchema)(it, sch)) {\n                    gen.var(schValid, true);\n                }\n                else {\n                    schCxt = cxt.subschema({\n                        keyword: \"oneOf\",\n                        schemaProp: i,\n                        compositeRule: true,\n                    }, schValid);\n                }\n                if (i > 0) {\n                    gen\n                        .if((0, codegen_1._) `${schValid} && ${valid}`)\n                        .assign(valid, false)\n                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)\n                        .else();\n                }\n                gen.if(schValid, () => {\n                    gen.assign(valid, true);\n                    gen.assign(passing, i);\n                    if (schCxt)\n                        cxt.mergeEvaluated(schCxt, codegen_1.Name);\n                });\n            });\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=oneOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: \"allOf\",\n    schemaType: \"array\",\n    code(cxt) {\n        const { gen, schema, it } = cxt;\n        /* istanbul ignore if */\n        if (!Array.isArray(schema))\n            throw new Error(\"ajv implementation error\");\n        const valid = gen.name(\"valid\");\n        schema.forEach((sch, i) => {\n            if ((0, util_1.alwaysValidSchema)(it, sch))\n                return;\n            const schCxt = cxt.subschema({ keyword: \"allOf\", schemaProp: i }, valid);\n            cxt.ok(valid);\n            cxt.mergeEvaluated(schCxt);\n        });\n    },\n};\nexports.default = def;\n//# sourceMappingURL=allOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params }) => (0, codegen_1.str) `must match \"${params.ifClause}\" schema`,\n    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,\n};\nconst def = {\n    keyword: \"if\",\n    schemaType: [\"object\", \"boolean\"],\n    trackErrors: true,\n    error,\n    code(cxt) {\n        const { gen, parentSchema, it } = cxt;\n        if (parentSchema.then === undefined && parentSchema.else === undefined) {\n            (0, util_1.checkStrictMode)(it, '\"if\" without \"then\" and \"else\" is ignored');\n        }\n        const hasThen = hasSchema(it, \"then\");\n        const hasElse = hasSchema(it, \"else\");\n        if (!hasThen && !hasElse)\n            return;\n        const valid = gen.let(\"valid\", true);\n        const schValid = gen.name(\"_valid\");\n        validateIf();\n        cxt.reset();\n        if (hasThen && hasElse) {\n            const ifClause = gen.let(\"ifClause\");\n            cxt.setParams({ ifClause });\n            gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause));\n        }\n        else if (hasThen) {\n            gen.if(schValid, validateClause(\"then\"));\n        }\n        else {\n            gen.if((0, codegen_1.not)(schValid), validateClause(\"else\"));\n        }\n        cxt.pass(valid, () => cxt.error(true));\n        function validateIf() {\n            const schCxt = cxt.subschema({\n                keyword: \"if\",\n                compositeRule: true,\n                createErrors: false,\n                allErrors: false,\n            }, schValid);\n            cxt.mergeEvaluated(schCxt);\n        }\n        function validateClause(keyword, ifClause) {\n            return () => {\n                const schCxt = cxt.subschema({ keyword }, schValid);\n                gen.assign(valid, schValid);\n                cxt.mergeValidEvaluated(schCxt, valid);\n                if (ifClause)\n                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);\n                else\n                    cxt.setParams({ ifClause: keyword });\n            };\n        }\n    },\n};\nfunction hasSchema(it, keyword) {\n    const schema = it.schema[keyword];\n    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);\n}\nexports.default = def;\n//# sourceMappingURL=if.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n    keyword: [\"then\", \"else\"],\n    schemaType: [\"object\", \"boolean\"],\n    code({ keyword, parentSchema, it }) {\n        if (parentSchema.if === undefined)\n            (0, util_1.checkStrictMode)(it, `\"${keyword}\" without \"if\" is ignored`);\n    },\n};\nexports.default = def;\n//# sourceMappingURL=thenElse.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst additionalItems_1 = require(\"./additionalItems\");\nconst prefixItems_1 = require(\"./prefixItems\");\nconst items_1 = require(\"./items\");\nconst items2020_1 = require(\"./items2020\");\nconst contains_1 = require(\"./contains\");\nconst dependencies_1 = require(\"./dependencies\");\nconst propertyNames_1 = require(\"./propertyNames\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst properties_1 = require(\"./properties\");\nconst patternProperties_1 = require(\"./patternProperties\");\nconst not_1 = require(\"./not\");\nconst anyOf_1 = require(\"./anyOf\");\nconst oneOf_1 = require(\"./oneOf\");\nconst allOf_1 = require(\"./allOf\");\nconst if_1 = require(\"./if\");\nconst thenElse_1 = require(\"./thenElse\");\nfunction getApplicator(draft2020 = false) {\n    const applicator = [\n        // any\n        not_1.default,\n        anyOf_1.default,\n        oneOf_1.default,\n        allOf_1.default,\n        if_1.default,\n        thenElse_1.default,\n        // object\n        propertyNames_1.default,\n        additionalProperties_1.default,\n        dependencies_1.default,\n        properties_1.default,\n        patternProperties_1.default,\n    ];\n    // array\n    if (draft2020)\n        applicator.push(prefixItems_1.default, items2020_1.default);\n    else\n        applicator.push(additionalItems_1.default, items_1.default);\n    applicator.push(contains_1.default);\n    return applicator;\n}\nexports.default = getApplicator;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n    message: ({ schemaCode }) => (0, codegen_1.str) `must match format \"${schemaCode}\"`,\n    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,\n};\nconst def = {\n    keyword: \"format\",\n    type: [\"number\", \"string\"],\n    schemaType: \"string\",\n    $data: true,\n    error,\n    code(cxt, ruleType) {\n        const { gen, data, $data, schema, schemaCode, it } = cxt;\n        const { opts, errSchemaPath, schemaEnv, self } = it;\n        if (!opts.validateFormats)\n            return;\n        if ($data)\n            validate$DataFormat();\n        else\n            validateFormat();\n        function validate$DataFormat() {\n            const fmts = gen.scopeValue(\"formats\", {\n                ref: self.formats,\n                code: opts.code.formats,\n            });\n            const fDef = gen.const(\"fDef\", (0, codegen_1._) `${fmts}[${schemaCode}]`);\n            const fType = gen.let(\"fType\");\n            const format = gen.let(\"format\");\n            // TODO simplify\n            gen.if((0, codegen_1._) `typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || \"string\"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `\"string\"`).assign(format, fDef));\n            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));\n            function unknownFmt() {\n                if (opts.strictSchema === false)\n                    return codegen_1.nil;\n                return (0, codegen_1._) `${schemaCode} && !${format}`;\n            }\n            function invalidFmt() {\n                const callFormat = schemaEnv.$async\n                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n                    : (0, codegen_1._) `${format}(${data})`;\n                const validData = (0, codegen_1._) `(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`;\n                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;\n            }\n        }\n        function validateFormat() {\n            const formatDef = self.formats[schema];\n            if (!formatDef) {\n                unknownFormat();\n                return;\n            }\n            if (formatDef === true)\n                return;\n            const [fmtType, format, fmtRef] = getFormat(formatDef);\n            if (fmtType === ruleType)\n                cxt.pass(validCondition());\n            function unknownFormat() {\n                if (opts.strictSchema === false) {\n                    self.logger.warn(unknownMsg());\n                    return;\n                }\n                throw new Error(unknownMsg());\n                function unknownMsg() {\n                    return `unknown format \"${schema}\" ignored in schema at path \"${errSchemaPath}\"`;\n                }\n            }\n            function getFormat(fmtDef) {\n                const code = fmtDef instanceof RegExp\n                    ? (0, codegen_1.regexpCode)(fmtDef)\n                    : opts.code.formats\n                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`\n                        : undefined;\n                const fmt = gen.scopeValue(\"formats\", { key: schema, ref: fmtDef, code });\n                if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n                    return [fmtDef.type || \"string\", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];\n                }\n                return [\"string\", fmtDef, fmt];\n            }\n            function validCondition() {\n                if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n                    if (!schemaEnv.$async)\n                        throw new Error(\"async format in sync schema\");\n                    return (0, codegen_1._) `await ${fmtRef}(${data})`;\n                }\n                return typeof format == \"function\" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;\n            }\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=format.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst format_1 = require(\"./format\");\nconst format = [format_1.default];\nexports.default = format;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.contentVocabulary = exports.metadataVocabulary = void 0;\nexports.metadataVocabulary = [\n    \"title\",\n    \"description\",\n    \"default\",\n    \"deprecated\",\n    \"readOnly\",\n    \"writeOnly\",\n    \"examples\",\n];\nexports.contentVocabulary = [\n    \"contentMediaType\",\n    \"contentEncoding\",\n    \"contentSchema\",\n];\n//# sourceMappingURL=metadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core_1 = require(\"./core\");\nconst validation_1 = require(\"./validation\");\nconst applicator_1 = require(\"./applicator\");\nconst format_1 = require(\"./format\");\nconst metadata_1 = require(\"./metadata\");\nconst draft7Vocabularies = [\n    core_1.default,\n    validation_1.default,\n    (0, applicator_1.default)(),\n    format_1.default,\n    metadata_1.metadataVocabulary,\n    metadata_1.contentVocabulary,\n];\nexports.default = draft7Vocabularies;\n//# sourceMappingURL=draft7.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DiscrError = void 0;\nvar DiscrError;\n(function (DiscrError) {\n    DiscrError[\"Tag\"] = \"tag\";\n    DiscrError[\"Mapping\"] = \"mapping\";\n})(DiscrError || (exports.DiscrError = DiscrError = {}));\n//# sourceMappingURL=types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst types_1 = require(\"../discriminator/types\");\nconst compile_1 = require(\"../../compile\");\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag\n        ? `tag \"${tagName}\" must be string`\n        : `value of tag \"${tagName}\" must be in oneOf`,\n    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n};\nconst def = {\n    keyword: \"discriminator\",\n    type: \"object\",\n    schemaType: \"object\",\n    error,\n    code(cxt) {\n        const { gen, data, schema, parentSchema, it } = cxt;\n        const { oneOf } = parentSchema;\n        if (!it.opts.discriminator) {\n            throw new Error(\"discriminator: requires discriminator option\");\n        }\n        const tagName = schema.propertyName;\n        if (typeof tagName != \"string\")\n            throw new Error(\"discriminator: requires propertyName\");\n        if (schema.mapping)\n            throw new Error(\"discriminator: mapping is not supported\");\n        if (!oneOf)\n            throw new Error(\"discriminator: requires oneOf keyword\");\n        const valid = gen.let(\"valid\", false);\n        const tag = gen.const(\"tag\", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);\n        gen.if((0, codegen_1._) `typeof ${tag} == \"string\"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));\n        cxt.ok(valid);\n        function validateMapping() {\n            const mapping = getMapping();\n            gen.if(false);\n            for (const tagValue in mapping) {\n                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);\n                gen.assign(valid, applyTagSchema(mapping[tagValue]));\n            }\n            gen.else();\n            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });\n            gen.endIf();\n        }\n        function applyTagSchema(schemaProp) {\n            const _valid = gen.name(\"valid\");\n            const schCxt = cxt.subschema({ keyword: \"oneOf\", schemaProp }, _valid);\n            cxt.mergeEvaluated(schCxt, codegen_1.Name);\n            return _valid;\n        }\n        function getMapping() {\n            var _a;\n            const oneOfMapping = {};\n            const topRequired = hasRequired(parentSchema);\n            let tagRequired = true;\n            for (let i = 0; i < oneOf.length; i++) {\n                let sch = oneOf[i];\n                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {\n                    const ref = sch.$ref;\n                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);\n                    if (sch instanceof compile_1.SchemaEnv)\n                        sch = sch.schema;\n                    if (sch === undefined)\n                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);\n                }\n                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];\n                if (typeof propSch != \"object\") {\n                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`);\n                }\n                tagRequired = tagRequired && (topRequired || hasRequired(sch));\n                addMappings(propSch, i);\n            }\n            if (!tagRequired)\n                throw new Error(`discriminator: \"${tagName}\" must be required`);\n            return oneOfMapping;\n            function hasRequired({ required }) {\n                return Array.isArray(required) && required.includes(tagName);\n            }\n            function addMappings(sch, i) {\n                if (sch.const) {\n                    addMapping(sch.const, i);\n                }\n                else if (sch.enum) {\n                    for (const tagValue of sch.enum) {\n                        addMapping(tagValue, i);\n                    }\n                }\n                else {\n                    throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`);\n                }\n            }\n            function addMapping(tagValue, i) {\n                if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n                    throw new Error(`discriminator: \"${tagName}\" values must be unique strings`);\n                }\n                oneOfMapping[tagValue] = i;\n            }\n        }\n    },\n};\nexports.default = def;\n//# sourceMappingURL=index.js.map","","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;\nconst core_1 = require(\"./core\");\nconst draft7_1 = require(\"./vocabularies/draft7\");\nconst discriminator_1 = require(\"./vocabularies/discriminator\");\nconst draft7MetaSchema = require(\"./refs/json-schema-draft-07.json\");\nconst META_SUPPORT_DATA = [\"/properties\"];\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\";\nclass Ajv extends core_1.default {\n    _addVocabularies() {\n        super._addVocabularies();\n        draft7_1.default.forEach((v) => this.addVocabulary(v));\n        if (this.opts.discriminator)\n            this.addKeyword(discriminator_1.default);\n    }\n    _addDefaultMetaSchema() {\n        super._addDefaultMetaSchema();\n        if (!this.opts.meta)\n            return;\n        const metaSchema = this.opts.$data\n            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n            : draft7MetaSchema;\n        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);\n        this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID;\n    }\n    defaultMeta() {\n        return (this.opts.defaultMeta =\n            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));\n    }\n}\nexports.Ajv = Ajv;\nmodule.exports = exports = Ajv;\nmodule.exports.Ajv = Ajv;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = Ajv;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nvar validation_error_1 = require(\"./runtime/validation_error\");\nObject.defineProperty(exports, \"ValidationError\", { enumerable: true, get: function () { return validation_error_1.default; } });\nvar ref_error_1 = require(\"./compile/ref_error\");\nObject.defineProperty(exports, \"MissingRefError\", { enumerable: true, get: function () { return ref_error_1.default; } });\n//# sourceMappingURL=ajv.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatNames = exports.fastFormats = exports.fullFormats = void 0;\nfunction fmtDef(validate, compare) {\n    return { validate, compare };\n}\nexports.fullFormats = {\n    // date: http://tools.ietf.org/html/rfc3339#section-5.6\n    date: fmtDef(date, compareDate),\n    // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n    time: fmtDef(getTime(true), compareTime),\n    \"date-time\": fmtDef(getDateTime(true), compareDateTime),\n    \"iso-time\": fmtDef(getTime(), compareIsoTime),\n    \"iso-date-time\": fmtDef(getDateTime(), compareIsoDateTime),\n    // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n    duration: /^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n    uri,\n    \"uri-reference\": /^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'\"()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n    // uri-template: https://tools.ietf.org/html/rfc6570\n    \"uri-template\": /^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i,\n    // For the source: https://gist.github.com/dperini/729294\n    // For test cases: https://mathiasbynens.be/demo/url-regex\n    url: /^(?:https?|ftp):\\/\\/(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)(?:\\.(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu,\n    email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n    hostname: /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i,\n    // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n    ipv4: /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/,\n    ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i,\n    regex,\n    // uuid: http://tools.ietf.org/html/rfc4122\n    uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n    // JSON-pointer: https://tools.ietf.org/html/rfc6901\n    // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n    \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n    \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n    // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n    \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n    // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n    // byte: https://github.com/miguelmota/is-base64\n    byte,\n    // signed 32 bit integer\n    int32: { type: \"number\", validate: validateInt32 },\n    // signed 64 bit integer\n    int64: { type: \"number\", validate: validateInt64 },\n    // C-type float\n    float: { type: \"number\", validate: validateNumber },\n    // C-type double\n    double: { type: \"number\", validate: validateNumber },\n    // hint to the UI to hide input strings\n    password: true,\n    // unchecked string payload\n    binary: true,\n};\nexports.fastFormats = {\n    ...exports.fullFormats,\n    date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n    time: fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i, compareTime),\n    \"date-time\": fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\dt(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i, compareDateTime),\n    \"iso-time\": fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i, compareIsoTime),\n    \"iso-date-time\": fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d[t\\s](?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i, compareIsoDateTime),\n    // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n    uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n    \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n    // email (sources from jsen validator):\n    // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n    // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n    email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,\n};\nexports.formatNames = Object.keys(exports.fullFormats);\nfunction isLeapYear(year) {\n    // https://tools.ietf.org/html/rfc3339#appendix-C\n    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nfunction date(str) {\n    // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n    const matches = DATE.exec(str);\n    if (!matches)\n        return false;\n    const year = +matches[1];\n    const month = +matches[2];\n    const day = +matches[3];\n    return (month >= 1 &&\n        month <= 12 &&\n        day >= 1 &&\n        day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));\n}\nfunction compareDate(d1, d2) {\n    if (!(d1 && d2))\n        return undefined;\n    if (d1 > d2)\n        return 1;\n    if (d1 < d2)\n        return -1;\n    return 0;\n}\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i;\nfunction getTime(strictTimeZone) {\n    return function time(str) {\n        const matches = TIME.exec(str);\n        if (!matches)\n            return false;\n        const hr = +matches[1];\n        const min = +matches[2];\n        const sec = +matches[3];\n        const tz = matches[4];\n        const tzSign = matches[5] === \"-\" ? -1 : 1;\n        const tzH = +(matches[6] || 0);\n        const tzM = +(matches[7] || 0);\n        if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz))\n            return false;\n        if (hr <= 23 && min <= 59 && sec < 60)\n            return true;\n        // leap second\n        const utcMin = min - tzM * tzSign;\n        const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);\n        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;\n    };\n}\nfunction compareTime(s1, s2) {\n    if (!(s1 && s2))\n        return undefined;\n    const t1 = new Date(\"2020-01-01T\" + s1).valueOf();\n    const t2 = new Date(\"2020-01-01T\" + s2).valueOf();\n    if (!(t1 && t2))\n        return undefined;\n    return t1 - t2;\n}\nfunction compareIsoTime(t1, t2) {\n    if (!(t1 && t2))\n        return undefined;\n    const a1 = TIME.exec(t1);\n    const a2 = TIME.exec(t2);\n    if (!(a1 && a2))\n        return undefined;\n    t1 = a1[1] + a1[2] + a1[3];\n    t2 = a2[1] + a2[2] + a2[3];\n    if (t1 > t2)\n        return 1;\n    if (t1 < t2)\n        return -1;\n    return 0;\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction getDateTime(strictTimeZone) {\n    const time = getTime(strictTimeZone);\n    return function date_time(str) {\n        // http://tools.ietf.org/html/rfc3339#section-5.6\n        const dateTime = str.split(DATE_TIME_SEPARATOR);\n        return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);\n    };\n}\nfunction compareDateTime(dt1, dt2) {\n    if (!(dt1 && dt2))\n        return undefined;\n    const d1 = new Date(dt1).valueOf();\n    const d2 = new Date(dt2).valueOf();\n    if (!(d1 && d2))\n        return undefined;\n    return d1 - d2;\n}\nfunction compareIsoDateTime(dt1, dt2) {\n    if (!(dt1 && dt2))\n        return undefined;\n    const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);\n    const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);\n    const res = compareDate(d1, d2);\n    if (res === undefined)\n        return undefined;\n    return res || compareTime(t1, t2);\n}\nconst NOT_URI_FRAGMENT = /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)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;\nfunction uri(str) {\n    // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n    return NOT_URI_FRAGMENT.test(str) && URI.test(str);\n}\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;\nfunction byte(str) {\n    BYTE.lastIndex = 0;\n    return BYTE.test(str);\n}\nconst MIN_INT32 = -(2 ** 31);\nconst MAX_INT32 = 2 ** 31 - 1;\nfunction validateInt32(value) {\n    return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;\n}\nfunction validateInt64(value) {\n    // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n    return Number.isInteger(value);\n}\nfunction validateNumber() {\n    return true;\n}\nconst Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n    if (Z_ANCHOR.test(str))\n        return false;\n    try {\n        new RegExp(str);\n        return true;\n    }\n    catch (e) {\n        return false;\n    }\n}\n//# sourceMappingURL=formats.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatLimitDefinition = void 0;\nconst ajv_1 = require(\"ajv\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n    formatMaximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n    formatMinimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n    formatExclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n    formatExclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`,\n    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nexports.formatLimitDefinition = {\n    keyword: Object.keys(KWDs),\n    type: \"string\",\n    schemaType: \"string\",\n    $data: true,\n    error,\n    code(cxt) {\n        const { gen, data, schemaCode, keyword, it } = cxt;\n        const { opts, self } = it;\n        if (!opts.validateFormats)\n            return;\n        const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, \"format\");\n        if (fCxt.$data)\n            validate$DataFormat();\n        else\n            validateFormat();\n        function validate$DataFormat() {\n            const fmts = gen.scopeValue(\"formats\", {\n                ref: self.formats,\n                code: opts.code.formats,\n            });\n            const fmt = gen.const(\"fmt\", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`);\n            cxt.fail$data((0, codegen_1.or)((0, codegen_1._) `typeof ${fmt} != \"object\"`, (0, codegen_1._) `${fmt} instanceof RegExp`, (0, codegen_1._) `typeof ${fmt}.compare != \"function\"`, compareCode(fmt)));\n        }\n        function validateFormat() {\n            const format = fCxt.schema;\n            const fmtDef = self.formats[format];\n            if (!fmtDef || fmtDef === true)\n                return;\n            if (typeof fmtDef != \"object\" ||\n                fmtDef instanceof RegExp ||\n                typeof fmtDef.compare != \"function\") {\n                throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`);\n            }\n            const fmt = gen.scopeValue(\"formats\", {\n                key: format,\n                ref: fmtDef,\n                code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined,\n            });\n            cxt.fail$data(compareCode(fmt));\n        }\n        function compareCode(fmt) {\n            return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;\n        }\n    },\n    dependencies: [\"format\"],\n};\nconst formatLimitPlugin = (ajv) => {\n    ajv.addKeyword(exports.formatLimitDefinition);\n    return ajv;\n};\nexports.default = formatLimitPlugin;\n//# sourceMappingURL=limit.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst formats_1 = require(\"./formats\");\nconst limit_1 = require(\"./limit\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst fullName = new codegen_1.Name(\"fullFormats\");\nconst fastName = new codegen_1.Name(\"fastFormats\");\nconst formatsPlugin = (ajv, opts = { keywords: true }) => {\n    if (Array.isArray(opts)) {\n        addFormats(ajv, opts, formats_1.fullFormats, fullName);\n        return ajv;\n    }\n    const [formats, exportName] = opts.mode === \"fast\" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];\n    const list = opts.formats || formats_1.formatNames;\n    addFormats(ajv, list, formats, exportName);\n    if (opts.keywords)\n        (0, limit_1.default)(ajv);\n    return ajv;\n};\nformatsPlugin.get = (name, mode = \"full\") => {\n    const formats = mode === \"fast\" ? formats_1.fastFormats : formats_1.fullFormats;\n    const f = formats[name];\n    if (!f)\n        throw new Error(`Unknown format \"${name}\"`);\n    return f;\n};\nfunction addFormats(ajv, list, fs, exportName) {\n    var _a;\n    var _b;\n    (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require(\"ajv-formats/dist/formats\").${exportName}`);\n    for (const f of list)\n        ajv.addFormat(f, fs[f]);\n}\nmodule.exports = exports = formatsPlugin;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = formatsPlugin;\n//# sourceMappingURL=index.js.map","/**\n * AJV-based JSON Schema validator provider\n */\nimport Ajv from 'ajv';\nimport _addFormats from 'ajv-formats';\nfunction createDefaultAjvInstance() {\n    const ajv = new Ajv({\n        strict: false,\n        validateFormats: true,\n        validateSchema: false,\n        allErrors: true\n    });\n    const addFormats = _addFormats;\n    addFormats(ajv);\n    return ajv;\n}\n/**\n * @example\n * ```typescript\n * // Use with default AJV instance (recommended)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Use with custom AJV instance\n * import { Ajv } from 'ajv';\n * const ajv = new Ajv({ strict: true, allErrors: true });\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\nexport class AjvJsonSchemaValidator {\n    /**\n     * Create an AJV validator\n     *\n     * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.\n     *\n     * @example\n     * ```typescript\n     * // Use default configuration (recommended for most cases)\n     * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n     * const validator = new AjvJsonSchemaValidator();\n     *\n     * // Or provide custom AJV instance for advanced configuration\n     * import { Ajv } from 'ajv';\n     * import addFormats from 'ajv-formats';\n     *\n     * const ajv = new Ajv({ validateFormats: true });\n     * addFormats(ajv);\n     * const validator = new AjvJsonSchemaValidator(ajv);\n     * ```\n     */\n    constructor(ajv) {\n        this._ajv = ajv ?? createDefaultAjvInstance();\n    }\n    /**\n     * Create a validator for the given JSON Schema\n     *\n     * The validator is compiled once and can be reused multiple times.\n     * If the schema has an $id, it will be cached by AJV automatically.\n     *\n     * @param schema - Standard JSON Schema object\n     * @returns A validator function that validates input data\n     */\n    getValidator(schema) {\n        // Check if schema has $id and is already compiled/cached\n        const ajvValidator = '$id' in schema && typeof schema.$id === 'string'\n            ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema))\n            : this._ajv.compile(schema);\n        return (input) => {\n            const valid = ajvValidator(input);\n            if (valid) {\n                return {\n                    valid: true,\n                    data: input,\n                    errorMessage: undefined\n                };\n            }\n            else {\n                return {\n                    valid: false,\n                    data: undefined,\n                    errorMessage: this._ajv.errorsText(ajvValidator.errors)\n                };\n            }\n        };\n    }\n}\n//# sourceMappingURL=ajv-provider.js.map","import { createMCPClient } from \"@ai-sdk/mcp\";\nimport { Experimental_StdioMCPTransport } from \"@ai-sdk/mcp/mcp-stdio\";\nimport { discoverAuthorizationServerMetadata, discoverAuthorizationServerMetadata as discoverAuthorizationServerMetadata$1, discoverOAuthProtectedResourceMetadata, discoverOAuthProtectedResourceMetadata as discoverOAuthProtectedResourceMetadata$1, discoverOAuthServerInfo, discoverOAuthServerInfo as discoverOAuthServerInfo$1, exchangeAuthorization, extractWWWAuthenticateParams, refreshAuthorization, registerClient, startAuthorization } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n//#region src/types.ts\nconst MCP = Symbol.for(\"keystroke.mcp\");\n//#endregion\n//#region src/define-mcp.ts\nfunction defineMcp(def) {\n\tconst key = def.key?.trim();\n\tif (!key) throw new Error(\"defineMcp requires key (e.g. defineMcp({ key: \\\"exa\\\", ... }))\");\n\tif (def.credentials?.length && !def.auth) throw new Error(`defineMcp(\"${key}\") declares credentials but no auth mapper`);\n\treturn {\n\t\t...def,\n\t\tkey,\n\t\t[MCP]: true\n\t};\n}\n//#endregion\n//#region src/is-mcp.ts\nfunction isMcp(value) {\n\treturn typeof value === \"object\" && value !== null && MCP in value && value[MCP] === true;\n}\n//#endregion\n//#region src/adapter.ts\nfunction createToolName(serverName, toolName) {\n\treturn `mcp__${sanitizeToolNamePart(serverName)}__${sanitizeToolNamePart(toolName)}`;\n}\nfunction sanitizeToolNamePart(value) {\n\treturn value.replace(/[^A-Za-z0-9_-]/g, \"_\").replace(/^_+|_+$/g, \"\") || \"unnamed\";\n}\nfunction normalizeInputSchema(schema) {\n\treturn {\n\t\t...schema,\n\t\ttype: schema.type ?? \"object\",\n\t\tproperties: schema.properties ?? {},\n\t\t...schema.required !== void 0 ? { required: schema.required } : {}\n\t};\n}\n/**\n* Re-key a native AI SDK {@link ToolSet} returned by `client.tools()` so every\n* tool is namespaced as `mcp__{server}__{tool}`. Prevents collisions across\n* servers and keeps tool names stable for prompts, filters, and tests.\n*/\nfunction prefixServerToolSet(serverName, toolSet) {\n\tconst prefixed = {};\n\tfor (const [name, tool] of Object.entries(toolSet)) {\n\t\tconst toolName = createToolName(serverName, name);\n\t\tif (prefixed[toolName]) throw new Error(`MCP tools from server \"${serverName}\" produced duplicate tool name \"${toolName}\".`);\n\t\tprefixed[toolName] = tool;\n\t}\n\treturn prefixed;\n}\n//#endregion\n//#region src/connect.ts\nasync function connectMcpServer(name, options) {\n\tconst url = options.url instanceof URL ? options.url : new URL(options.url);\n\tconst client = await createMCPClient({\n\t\ttransport: {\n\t\t\ttype: options.transport === \"sse\" ? \"sse\" : \"http\",\n\t\t\turl: url.toString(),\n\t\t\t...options.headers ? { headers: options.headers } : {},\n\t\t\t...options.fetch ? { fetch: options.fetch } : {}\n\t\t},\n\t\tclientName: options.clientName ?? \"keystroke\",\n\t\t...options.clientVersion ? { version: options.clientVersion } : {}\n\t});\n\ttry {\n\t\treturn {\n\t\t\tname,\n\t\t\ttoolSet: prefixServerToolSet(name, await client.tools()),\n\t\t\tclient,\n\t\t\tclose: () => client.close()\n\t\t};\n\t} catch (error) {\n\t\tawait client.close().catch(() => void 0);\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/connect-stdio.ts\nasync function connectMcpStdio(name, options) {\n\tconst client = await createMCPClient({\n\t\ttransport: new Experimental_StdioMCPTransport({\n\t\t\tcommand: options.command,\n\t\t\targs: options.args,\n\t\t\tenv: options.env,\n\t\t\tcwd: options.cwd,\n\t\t\tstderr: options.stderr\n\t\t}),\n\t\tclientName: options.clientName ?? \"keystroke\",\n\t\t...options.clientVersion ? { version: options.clientVersion } : {}\n\t});\n\ttry {\n\t\treturn {\n\t\t\tname,\n\t\t\ttoolSet: prefixServerToolSet(name, await client.tools()),\n\t\t\tclient,\n\t\t\tclose: () => client.close()\n\t\t};\n\t} catch (error) {\n\t\tawait client.close().catch(() => void 0);\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/connect-definition.ts\nasync function connectMcpDefinition(def, auth) {\n\tconst common = {\n\t\tclientName: def.clientName,\n\t\tclientVersion: def.clientVersion\n\t};\n\tif (def.transport.type === \"http\") return connectMcpServer(def.key, {\n\t\turl: applyAuthSearchParams(def.transport.url, auth?.searchParams),\n\t\ttransport: def.transport.transport,\n\t\theaders: auth?.headers,\n\t\trequestInit: def.requestInit,\n\t\tfetch: def.fetch,\n\t\t...common\n\t});\n\treturn connectMcpStdio(def.key, {\n\t\tcommand: def.transport.command,\n\t\targs: def.transport.args,\n\t\tcwd: def.transport.cwd,\n\t\tstderr: def.transport.stderr,\n\t\tenv: auth?.env,\n\t\t...common\n\t});\n}\nfunction applyAuthSearchParams(url, searchParams) {\n\tif (!searchParams) return url;\n\tconst resolved = url instanceof URL ? new URL(url) : new URL(url);\n\tfor (const [key, value] of Object.entries(searchParams)) resolved.searchParams.set(key, value);\n\treturn resolved;\n}\n//#endregion\n//#region src/oauth-scopes.ts\n/** Union OAuth scope names from metadata sources, preserving first-seen order. */\nfunction mergeOAuthScopes(...lists) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst result = [];\n\tfor (const list of lists) {\n\t\tif (!list?.length) continue;\n\t\tfor (const scope of list) {\n\t\t\tconst trimmed = scope.trim();\n\t\t\tif (trimmed && !seen.has(trimmed)) {\n\t\t\t\tseen.add(trimmed);\n\t\t\t\tresult.push(trimmed);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n//#endregion\n//#region src/public-http-url.ts\n/** Thrown when a URL is not safe for server-side outbound fetch (SSRF guard). */\nvar PublicHttpUrlError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"PublicHttpUrlError\";\n\t}\n};\nconst BLOCKED_HOSTNAMES = new Set([\n\t\"localhost\",\n\t\"metadata.google.internal\",\n\t\"metadata.goog\"\n]);\nfunction normalizeHostname(hostname) {\n\tconst trimmed = hostname.trim().toLowerCase();\n\tif (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) return trimmed.slice(1, -1);\n\treturn trimmed;\n}\nfunction parseIpv4Octets(hostname) {\n\tconst parts = hostname.split(\".\");\n\tif (parts.length !== 4) return null;\n\tconst octets = [];\n\tfor (const part of parts) {\n\t\tif (!/^\\d+$/.test(part)) return null;\n\t\tconst value = Number(part);\n\t\tif (value > 255) return null;\n\t\toctets.push(value);\n\t}\n\treturn octets;\n}\nfunction isPrivateIpv4(octets) {\n\tconst a = octets[0];\n\tconst b = octets[1];\n\tif (a === void 0 || b === void 0) return true;\n\tif (a === 0 || a === 10 || a === 127) return true;\n\tif (a === 169 && b === 254) return true;\n\tif (a === 172 && b >= 16 && b <= 31) return true;\n\tif (a === 192 && b === 168) return true;\n\treturn false;\n}\nfunction isPrivateIpv6(hostname) {\n\tif (hostname === \"::1\") return true;\n\tif (hostname.startsWith(\"fe80:\")) return true;\n\tif (hostname.startsWith(\"fc\") || hostname.startsWith(\"fd\")) return true;\n\treturn false;\n}\nfunction isBlockedHost(hostname) {\n\tif (BLOCKED_HOSTNAMES.has(hostname)) return true;\n\tif (hostname.endsWith(\".localhost\")) return true;\n\tconst ipv4 = parseIpv4Octets(hostname);\n\tif (ipv4) return isPrivateIpv4(ipv4);\n\tif (hostname.includes(\":\")) return isPrivateIpv6(hostname);\n\treturn false;\n}\n/** Validate that a URL is safe to fetch from the platform (http/https, public hosts only). */\nfunction assertPublicHttpUrl(urlString) {\n\tlet url;\n\ttry {\n\t\turl = new URL(urlString.trim());\n\t} catch {\n\t\tthrow new PublicHttpUrlError(\"Invalid URL\");\n\t}\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new PublicHttpUrlError(\"URL must use http or https\");\n\tif (isBlockedHost(normalizeHostname(url.hostname))) throw new PublicHttpUrlError(\"URL host is not allowed\");\n\treturn url;\n}\n//#endregion\n//#region src/probe.ts\nfunction resourceNameFromMetadata(metadata) {\n\treturn metadata?.resource_name?.trim() || void 0;\n}\nasync function probeUnauthenticatedStatus(url, fetchFn) {\n\ttry {\n\t\tconst response = await fetchFn(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { Accept: \"application/json, text/event-stream\" }\n\t\t});\n\t\tconst wwwAuthenticate = response.headers.get(\"www-authenticate\");\n\t\tawait response.body?.cancel();\n\t\treturn {\n\t\t\tstatus: response.status,\n\t\t\twwwAuthenticate\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\nfunction scopesFromMetadata(metadata) {\n\tif (!metadata?.scopes_supported?.length) return [];\n\treturn metadata.scopes_supported;\n}\nfunction logProbeFallback(phase, error) {\n\tif (process.env.NODE_ENV === \"test\" || process.env.VITEST) return;\n\tconst detail = error instanceof Error ? error.message : String(error);\n\tconsole.warn(`[mcp-probe] ${phase} failed: ${detail}`);\n}\nasync function probeMcpAuth(url, fetchFn = fetch) {\n\tassertPublicHttpUrl(url);\n\tconst serverUrl = new URL(url);\n\tconst { status, wwwAuthenticate } = await probeUnauthenticatedStatus(url, fetchFn);\n\tlet resourceMetadataUrl;\n\tif (wwwAuthenticate) resourceMetadataUrl = extractWWWAuthenticateParams(new Response(null, { headers: { \"www-authenticate\": wwwAuthenticate } })).resourceMetadataUrl?.toString();\n\ttry {\n\t\tconst discovered = await discoverOAuthServerInfo$1(serverUrl, {\n\t\t\tfetchFn,\n\t\t\t...resourceMetadataUrl ? { resourceMetadataUrl: new URL(resourceMetadataUrl) } : {}\n\t\t});\n\t\tconst metadata = discovered.authorizationServerMetadata;\n\t\tif (metadata?.authorization_endpoint && metadata.token_endpoint) return {\n\t\t\turl,\n\t\t\tmode: \"oauth\",\n\t\t\tunauthenticatedStatus: status,\n\t\t\toauth: {\n\t\t\t\tissuer: metadata.issuer,\n\t\t\t\tauthorizationEndpoint: metadata.authorization_endpoint,\n\t\t\t\ttokenEndpoint: metadata.token_endpoint,\n\t\t\t\tregistrationEndpoint: metadata.registration_endpoint,\n\t\t\t\tscopes: mergeOAuthScopes(scopesFromMetadata(metadata), scopesFromMetadata(discovered.resourceMetadata)),\n\t\t\t\tresource: discovered.resourceMetadata?.resource,\n\t\t\t\tresourceName: resourceNameFromMetadata(discovered.resourceMetadata)\n\t\t\t}\n\t\t};\n\t} catch (error) {\n\t\tlogProbeFallback(\"discoverOAuthServerInfo\", error);\n\t}\n\ttry {\n\t\tconst protectedResource = await discoverOAuthProtectedResourceMetadata$1(serverUrl, {}, fetchFn);\n\t\tconst metadata = await discoverAuthorizationServerMetadata$1(protectedResource.authorization_servers?.[0] ?? serverUrl.origin, { fetchFn });\n\t\tif (metadata?.authorization_endpoint && metadata.token_endpoint) return {\n\t\t\turl,\n\t\t\tmode: \"oauth\",\n\t\t\tunauthenticatedStatus: status,\n\t\t\toauth: {\n\t\t\t\tissuer: metadata.issuer,\n\t\t\t\tauthorizationEndpoint: metadata.authorization_endpoint,\n\t\t\t\ttokenEndpoint: metadata.token_endpoint,\n\t\t\t\tregistrationEndpoint: metadata.registration_endpoint,\n\t\t\t\tscopes: mergeOAuthScopes(scopesFromMetadata(metadata), scopesFromMetadata(protectedResource)),\n\t\t\t\tresource: protectedResource.resource,\n\t\t\t\tresourceName: resourceNameFromMetadata(protectedResource)\n\t\t\t}\n\t\t};\n\t} catch (error) {\n\t\tlogProbeFallback(\"discoverOAuthProtectedResourceMetadata\", error);\n\t}\n\tif (status === 401 || status === 403) return {\n\t\turl,\n\t\tmode: \"token\",\n\t\tunauthenticatedStatus: status,\n\t\tscheme: \"BEARER_TOKEN\"\n\t};\n\treturn {\n\t\turl,\n\t\tmode: \"none\",\n\t\tunauthenticatedStatus: status\n\t};\n}\n//#endregion\n//#region src/probe-server-info.ts\n/** Best-effort server metadata for no-auth MCP servers (initialize handshake). */\nasync function probeMcpServerInfo(url, fetchFn = fetch) {\n\tconst client = new Client({\n\t\tname: \"keystroke\",\n\t\tversion: \"0.0.0\"\n\t});\n\tconst transport = new StreamableHTTPClientTransport(new URL(url), { fetch: fetchFn });\n\ttry {\n\t\tawait client.connect(transport);\n\t\tconst info = client.getServerVersion();\n\t\tif (!info) return;\n\t\treturn {\n\t\t\tname: info.name,\n\t\t\ttitle: info.title,\n\t\t\tdescription: info.description,\n\t\t\tversion: info.version\n\t\t};\n\t} catch {\n\t\treturn;\n\t} finally {\n\t\tawait client.close().catch(() => void 0);\n\t}\n}\n//#endregion\n//#region src/read-client.ts\n/**\n* Connect a read-only MCP client over Streamable HTTP, run `fn`, and always close.\n*\n* For public, no-auth MCP servers (e.g. the Mintlify docs search server). Mirrors\n* `probeMcpServerInfo`: the SDK client drives the `initialize` handshake, so callers\n* just `callTool` / `readResource`.\n*/\nasync function withMcpReadClient(url, fn) {\n\tconst client = new Client({\n\t\tname: \"keystroke-cli\",\n\t\tversion: \"0.0.0\"\n\t});\n\tconst transport = new StreamableHTTPClientTransport(url instanceof URL ? url : new URL(url));\n\ttry {\n\t\tawait client.connect(transport);\n\t\treturn await fn(client);\n\t} finally {\n\t\tawait client.close().catch(() => void 0);\n\t}\n}\n//#endregion\nexport { MCP, PublicHttpUrlError, assertPublicHttpUrl, connectMcpDefinition, connectMcpServer, connectMcpStdio, createToolName, defineMcp, discoverAuthorizationServerMetadata, discoverOAuthProtectedResourceMetadata, discoverOAuthServerInfo, exchangeAuthorization, isMcp, mergeOAuthScopes, normalizeInputSchema, prefixServerToolSet, probeMcpAuth, probeMcpServerInfo, refreshAuthorization, registerClient, startAuthorization, withMcpReadClient };\n\n//# sourceMappingURL=index.mjs.map","import { boolean, index, integer, jsonb, pgTable, text, timestamp } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from \"drizzle-orm/sqlite-core\";\n//#region src/client/context.ts\nlet handle;\nfunction isDatabaseInitialized() {\n\treturn handle !== void 0;\n}\nfunction getDatabaseHandle() {\n\tif (!handle) throw new Error(\"Database not initialized. Call initDatabase() before getDb().\");\n\treturn handle;\n}\nfunction setDatabaseHandle(next) {\n\thandle = next;\n}\nfunction getDbFromContext() {\n\treturn getDatabaseHandle().db;\n}\n//#endregion\n//#region src/schema/tables/users.ts\nconst users = pgTable(\"users\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\temail: text(\"email\").notNull().unique(),\n\temailVerified: boolean(\"email_verified\").notNull(),\n\timage: text(\"image\"),\n\tpreferences: jsonb(\"preferences\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n});\nconst usersSqlite = sqliteTable(\"users\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\temail: text$1(\"email\").notNull().unique(),\n\temailVerified: integer$1(\"email_verified\", { mode: \"boolean\" }).notNull(),\n\timage: text$1(\"image\"),\n\tpreferences: text$1(\"preferences\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/auth-accounts.ts\nconst authAccounts = pgTable(\"accounts\", {\n\tid: text(\"id\").primaryKey(),\n\taccountId: text(\"account_id\").notNull(),\n\tproviderId: text(\"provider_id\").notNull(),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\taccessToken: text(\"access_token\"),\n\trefreshToken: text(\"refresh_token\"),\n\tidToken: text(\"id_token\"),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\trefreshTokenExpiresAt: timestamp(\"refresh_token_expires_at\", { withTimezone: true }),\n\tscope: text(\"scope\"),\n\tpassword: text(\"password\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"account_user_id_idx\").on(table.userId)]);\nconst authAccountsSqlite = sqliteTable(\"accounts\", {\n\tid: text$1(\"id\").primaryKey(),\n\taccountId: text$1(\"account_id\").notNull(),\n\tproviderId: text$1(\"provider_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\taccessToken: text$1(\"access_token\"),\n\trefreshToken: text$1(\"refresh_token\"),\n\tidToken: text$1(\"id_token\"),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\trefreshTokenExpiresAt: integer$1(\"refresh_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tscope: text$1(\"scope\"),\n\tpassword: text$1(\"password\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"account_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/auth-device-codes.ts\nconst authDeviceCodes = pgTable(\"device_auth_codes\", {\n\tid: text(\"id\").primaryKey(),\n\tdeviceCode: text(\"device_code\").notNull(),\n\tuserCode: text(\"user_code\").notNull(),\n\tuserId: text(\"user_id\"),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\tstatus: text(\"status\").notNull(),\n\tlastPolledAt: timestamp(\"last_polled_at\", { withTimezone: true }),\n\tpollingInterval: integer(\"polling_interval\"),\n\tclientId: text(\"client_id\"),\n\tscope: text(\"scope\")\n});\nconst authDeviceCodesSqlite = sqliteTable(\"device_auth_codes\", {\n\tid: text$1(\"id\").primaryKey(),\n\tdeviceCode: text$1(\"device_code\").notNull(),\n\tuserCode: text$1(\"user_code\").notNull(),\n\tuserId: text$1(\"user_id\"),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tstatus: text$1(\"status\").notNull(),\n\tlastPolledAt: integer$1(\"last_polled_at\", { mode: \"timestamp_ms\" }),\n\tpollingInterval: integer$1(\"polling_interval\"),\n\tclientId: text$1(\"client_id\"),\n\tscope: text$1(\"scope\")\n});\n//#endregion\n//#region src/schema/tables/auth-jwks.ts\nconst authJwks = pgTable(\"jwks\", {\n\tid: text(\"id\").primaryKey(),\n\tpublicKey: text(\"public_key\").notNull(),\n\tprivateKey: text(\"private_key\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true })\n});\nconst authJwksSqlite = sqliteTable(\"jwks\", {\n\tid: text$1(\"id\").primaryKey(),\n\tpublicKey: text$1(\"public_key\").notNull(),\n\tprivateKey: text$1(\"private_key\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" })\n});\n//#endregion\n//#region src/schema/tables/auth-sessions.ts\nconst authSessions = pgTable(\"sessions\", {\n\tid: text(\"id\").primaryKey(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\ttoken: text(\"token\").notNull().unique(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tipAddress: text(\"ip_address\"),\n\tuserAgent: text(\"user_agent\"),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" })\n}, (table) => [index(\"session_user_id_idx\").on(table.userId)]);\nconst authSessionsSqlite = sqliteTable(\"sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\ttoken: text$1(\"token\").notNull().unique(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tipAddress: text$1(\"ip_address\"),\n\tuserAgent: text$1(\"user_agent\"),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" })\n}, (table) => [index$1(\"session_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/auth-verifications.ts\nconst authVerifications = pgTable(\"verification\", {\n\tid: text(\"id\").primaryKey(),\n\tidentifier: text(\"identifier\").notNull(),\n\tvalue: text(\"value\").notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"verification_identifier_idx\").on(table.identifier)]);\nconst authVerificationsSqlite = sqliteTable(\"verification\", {\n\tid: text$1(\"id\").primaryKey(),\n\tidentifier: text$1(\"identifier\").notNull(),\n\tvalue: text$1(\"value\").notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"verification_identifier_idx\").on(table.identifier)]);\n//#endregion\n//#region src/schema/tables/mcp-oauth.ts\n/**\n* Tables backing keystroke as an OAuth 2.1 Authorization Server for the\n* Universal MCP server: dynamically-registered MCP/AI clients, their issued\n* access/refresh tokens, and consent records.\n*\n* NOT to be confused with `oauth_apps` / `oauth_connections`, which model the\n* inverse — keystroke as an OAuth *client* storing our users' connections to\n* third-party providers. These `mcp_oauth_*` tables are the provider side.\n*\n* Wired to Better Auth via the Drizzle adapter (`authSchemaFor`). Better Auth\n* addresses these by its fixed model names (`oauthApplication`,\n* `oauthAccessToken`, `oauthConsent`) and by field name (the JS property keys\n* below); the physical table/column names are ours to choose.\n*\n* Note: access/refresh tokens are stored as opaque plaintext bearer strings\n* (the Better Auth mcp plugin looks them up directly and cannot hash them),\n* consistent with how the `sessions` table stores session tokens. They are\n* short-lived; rely on DB access controls + at-rest encryption.\n*/\nconst mcpOauthClient = pgTable(\"mcp_oauth_client\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\ticon: text(\"icon\"),\n\tmetadata: text(\"metadata\"),\n\tclientId: text(\"client_id\").notNull().unique(),\n\tclientSecret: text(\"client_secret\"),\n\tredirectUrls: text(\"redirect_urls\").notNull(),\n\ttype: text(\"type\").notNull(),\n\tdisabled: boolean(\"disabled\").notNull().default(false),\n\tuserId: text(\"user_id\").references(() => users.id, { onDelete: \"cascade\" }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"mcp_oauth_client_user_id_idx\").on(table.userId)]);\nconst mcpOauthClientSqlite = sqliteTable(\"mcp_oauth_client\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\ticon: text$1(\"icon\"),\n\tmetadata: text$1(\"metadata\"),\n\tclientId: text$1(\"client_id\").notNull().unique(),\n\tclientSecret: text$1(\"client_secret\"),\n\tredirectUrls: text$1(\"redirect_urls\").notNull(),\n\ttype: text$1(\"type\").notNull(),\n\tdisabled: integer$1(\"disabled\", { mode: \"boolean\" }).notNull().default(false),\n\tuserId: text$1(\"user_id\").references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"mcp_oauth_client_user_id_idx\").on(table.userId)]);\nconst mcpOauthAccessToken = pgTable(\"mcp_oauth_access_token\", {\n\tid: text(\"id\").primaryKey(),\n\taccessToken: text(\"access_token\").notNull().unique(),\n\trefreshToken: text(\"refresh_token\").unique(),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\trefreshTokenExpiresAt: timestamp(\"refresh_token_expires_at\", { withTimezone: true }),\n\tclientId: text(\"client_id\").notNull(),\n\tuserId: text(\"user_id\").references(() => users.id, { onDelete: \"cascade\" }),\n\tscopes: text(\"scopes\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"mcp_oauth_access_token_client_id_idx\").on(table.clientId), index(\"mcp_oauth_access_token_user_id_idx\").on(table.userId)]);\nconst mcpOauthAccessTokenSqlite = sqliteTable(\"mcp_oauth_access_token\", {\n\tid: text$1(\"id\").primaryKey(),\n\taccessToken: text$1(\"access_token\").notNull().unique(),\n\trefreshToken: text$1(\"refresh_token\").unique(),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\trefreshTokenExpiresAt: integer$1(\"refresh_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tclientId: text$1(\"client_id\").notNull(),\n\tuserId: text$1(\"user_id\").references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tscopes: text$1(\"scopes\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"mcp_oauth_access_token_client_id_idx\").on(table.clientId), index$1(\"mcp_oauth_access_token_user_id_idx\").on(table.userId)]);\nconst mcpOauthConsent = pgTable(\"mcp_oauth_consent\", {\n\tid: text(\"id\").primaryKey(),\n\tclientId: text(\"client_id\").notNull(),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\tscopes: text(\"scopes\"),\n\tconsentGiven: boolean(\"consent_given\").notNull().default(false),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"mcp_oauth_consent_client_id_idx\").on(table.clientId), index(\"mcp_oauth_consent_user_id_idx\").on(table.userId)]);\nconst mcpOauthConsentSqlite = sqliteTable(\"mcp_oauth_consent\", {\n\tid: text$1(\"id\").primaryKey(),\n\tclientId: text$1(\"client_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tscopes: text$1(\"scopes\"),\n\tconsentGiven: integer$1(\"consent_given\", { mode: \"boolean\" }).notNull().default(false),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"mcp_oauth_consent_client_id_idx\").on(table.clientId), index$1(\"mcp_oauth_consent_user_id_idx\").on(table.userId)]);\n//#endregion\nexport { setDatabaseHandle as S, users as _, mcpOauthConsent as a, getDbFromContext as b, authVerificationsSqlite as c, authJwks as d, authJwksSqlite as f, authAccountsSqlite as g, authAccounts as h, mcpOauthClientSqlite as i, authSessions as l, authDeviceCodesSqlite as m, mcpOauthAccessTokenSqlite as n, mcpOauthConsentSqlite as o, authDeviceCodes as p, mcpOauthClient as r, authVerifications as s, mcpOauthAccessToken as t, authSessionsSqlite as u, usersSqlite as v, isDatabaseInitialized as x, getDatabaseHandle as y };\n\n//# sourceMappingURL=mcp-oauth-SRTcHMWZ.mjs.map","","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getKeyIndexes = exports.hasFlag = exports.exists = exports.list = void 0;\nconst commands_json_1 = __importDefault(require(\"./commands.json\"));\n/**\n * Redis command list\n *\n * All commands are lowercased.\n */\nexports.list = Object.keys(commands_json_1.default);\nconst flags = {};\nexports.list.forEach((commandName) => {\n    flags[commandName] = commands_json_1.default[commandName].flags.reduce(function (flags, flag) {\n        flags[flag] = true;\n        return flags;\n    }, {});\n});\n/**\n * Check if the command exists\n */\nfunction exists(commandName, options) {\n    commandName = (options === null || options === void 0 ? void 0 : options.caseInsensitive)\n        ? String(commandName).toLowerCase()\n        : commandName;\n    return Boolean(commands_json_1.default[commandName]);\n}\nexports.exists = exists;\n/**\n * Check if the command has the flag\n *\n * Some of possible flags: readonly, noscript, loading\n */\nfunction hasFlag(commandName, flag, options) {\n    commandName = (options === null || options === void 0 ? void 0 : options.nameCaseInsensitive)\n        ? String(commandName).toLowerCase()\n        : commandName;\n    if (!flags[commandName]) {\n        throw new Error(\"Unknown command \" + commandName);\n    }\n    return Boolean(flags[commandName][flag]);\n}\nexports.hasFlag = hasFlag;\n/**\n * Get indexes of keys in the command arguments\n *\n * @example\n * ```javascript\n * getKeyIndexes('set', ['key', 'value']) // [0]\n * getKeyIndexes('mget', ['key1', 'key2']) // [0, 1]\n * ```\n */\nfunction getKeyIndexes(commandName, args, options) {\n    commandName = (options === null || options === void 0 ? void 0 : options.nameCaseInsensitive)\n        ? String(commandName).toLowerCase()\n        : commandName;\n    const command = commands_json_1.default[commandName];\n    if (!command) {\n        throw new Error(\"Unknown command \" + commandName);\n    }\n    if (!Array.isArray(args)) {\n        throw new Error(\"Expect args to be an array\");\n    }\n    const keys = [];\n    const parseExternalKey = Boolean(options && options.parseExternalKey);\n    const takeDynamicKeys = (args, startIndex) => {\n        const keys = [];\n        const keyStop = Number(args[startIndex]);\n        for (let i = 0; i < keyStop; i++) {\n            keys.push(i + startIndex + 1);\n        }\n        return keys;\n    };\n    const takeKeyAfterToken = (args, startIndex, token) => {\n        for (let i = startIndex; i < args.length - 1; i += 1) {\n            if (String(args[i]).toLowerCase() === token.toLowerCase()) {\n                return i + 1;\n            }\n        }\n        return null;\n    };\n    switch (commandName) {\n        case \"zunionstore\":\n        case \"zinterstore\":\n        case \"zdiffstore\":\n            keys.push(0, ...takeDynamicKeys(args, 1));\n            break;\n        case \"eval\":\n        case \"evalsha\":\n        case \"eval_ro\":\n        case \"evalsha_ro\":\n        case \"fcall\":\n        case \"fcall_ro\":\n        case \"blmpop\":\n        case \"bzmpop\":\n            keys.push(...takeDynamicKeys(args, 1));\n            break;\n        case \"sintercard\":\n        case \"lmpop\":\n        case \"zunion\":\n        case \"zinter\":\n        case \"zmpop\":\n        case \"zintercard\":\n        case \"zdiff\": {\n            keys.push(...takeDynamicKeys(args, 0));\n            break;\n        }\n        case \"msetex\": {\n            const numKeys = Number(args[0]);\n            for (let i = 0; i < numKeys; i++) {\n                keys.push(1 + i * 2);\n            }\n            break;\n        }\n        case \"georadius\": {\n            keys.push(0);\n            const storeKey = takeKeyAfterToken(args, 5, \"STORE\");\n            if (storeKey)\n                keys.push(storeKey);\n            const distKey = takeKeyAfterToken(args, 5, \"STOREDIST\");\n            if (distKey)\n                keys.push(distKey);\n            break;\n        }\n        case \"georadiusbymember\": {\n            keys.push(0);\n            const storeKey = takeKeyAfterToken(args, 4, \"STORE\");\n            if (storeKey)\n                keys.push(storeKey);\n            const distKey = takeKeyAfterToken(args, 4, \"STOREDIST\");\n            if (distKey)\n                keys.push(distKey);\n            break;\n        }\n        case \"sort\":\n        case \"sort_ro\":\n            keys.push(0);\n            for (let i = 1; i < args.length - 1; i++) {\n                let arg = args[i];\n                if (typeof arg !== \"string\") {\n                    continue;\n                }\n                const directive = arg.toUpperCase();\n                if (directive === \"GET\") {\n                    i += 1;\n                    arg = args[i];\n                    if (arg !== \"#\") {\n                        if (parseExternalKey) {\n                            keys.push([i, getExternalKeyNameLength(arg)]);\n                        }\n                        else {\n                            keys.push(i);\n                        }\n                    }\n                }\n                else if (directive === \"BY\") {\n                    i += 1;\n                    if (parseExternalKey) {\n                        keys.push([i, getExternalKeyNameLength(args[i])]);\n                    }\n                    else {\n                        keys.push(i);\n                    }\n                }\n                else if (directive === \"STORE\") {\n                    i += 1;\n                    keys.push(i);\n                }\n            }\n            break;\n        case \"migrate\":\n            if (args[2] === \"\") {\n                for (let i = 5; i < args.length - 1; i++) {\n                    const arg = args[i];\n                    if (typeof arg === \"string\" && arg.toUpperCase() === \"KEYS\") {\n                        for (let j = i + 1; j < args.length; j++) {\n                            keys.push(j);\n                        }\n                        break;\n                    }\n                }\n            }\n            else {\n                keys.push(2);\n            }\n            break;\n        case \"xreadgroup\":\n        case \"xread\":\n            // Keys are 1st half of the args after STREAMS argument.\n            for (let i = commandName === \"xread\" ? 0 : 3; i < args.length - 1; i++) {\n                if (String(args[i]).toUpperCase() === \"STREAMS\") {\n                    for (let j = i + 1; j <= i + (args.length - 1 - i) / 2; j++) {\n                        keys.push(j);\n                    }\n                    break;\n                }\n            }\n            break;\n        default:\n            // Step has to be at least one in this case, otherwise the command does\n            // not contain a key.\n            if (command.step > 0) {\n                const keyStart = command.keyStart - 1;\n                const keyStop = command.keyStop > 0\n                    ? command.keyStop\n                    : args.length + command.keyStop + 1;\n                for (let i = keyStart; i < keyStop; i += command.step) {\n                    keys.push(i);\n                }\n            }\n            break;\n    }\n    return keys;\n}\nexports.getKeyIndexes = getKeyIndexes;\nfunction getExternalKeyNameLength(key) {\n    if (typeof key !== \"string\") {\n        key = String(key);\n    }\n    const hashPos = key.indexOf(\"->\");\n    return hashPos === -1 ? key.length : hashPos;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.tryCatch = exports.errorObj = void 0;\n//Try catch is not supported in optimizing\n//compiler, so it is isolated\nexports.errorObj = { e: {} };\nlet tryCatchTarget;\nfunction tryCatcher(err, val) {\n    try {\n        const target = tryCatchTarget;\n        tryCatchTarget = null;\n        return target.apply(this, arguments);\n    }\n    catch (e) {\n        exports.errorObj.e = e;\n        return exports.errorObj;\n    }\n}\nfunction tryCatch(fn) {\n    tryCatchTarget = fn;\n    return tryCatcher;\n}\nexports.tryCatch = tryCatch;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"./utils\");\nfunction throwLater(e) {\n    setTimeout(function () {\n        throw e;\n    }, 0);\n}\nfunction asCallback(promise, nodeback, options) {\n    if (typeof nodeback === \"function\") {\n        promise.then((val) => {\n            let ret;\n            if (options !== undefined &&\n                Object(options).spread &&\n                Array.isArray(val)) {\n                ret = utils_1.tryCatch(nodeback).apply(undefined, [null].concat(val));\n            }\n            else {\n                ret =\n                    val === undefined\n                        ? utils_1.tryCatch(nodeback)(null)\n                        : utils_1.tryCatch(nodeback)(null, val);\n            }\n            if (ret === utils_1.errorObj) {\n                throwLater(ret.e);\n            }\n        }, (cause) => {\n            if (!cause) {\n                const newReason = new Error(cause + \"\");\n                Object.assign(newReason, { cause });\n                cause = newReason;\n            }\n            const ret = utils_1.tryCatch(nodeback)(cause);\n            if (ret === utils_1.errorObj) {\n                throwLater(ret.e);\n            }\n        });\n    }\n    return promise;\n}\nexports.default = asCallback;\n","'use strict'\n\nconst assert = require('assert')\nconst util = require('util')\n\n// RedisError\n\nfunction RedisError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  Error.captureStackTrace(this, this.constructor)\n}\n\nutil.inherits(RedisError, Error)\n\nObject.defineProperty(RedisError.prototype, 'name', {\n  value: 'RedisError',\n  configurable: true,\n  writable: true\n})\n\n// ParserError\n\nfunction ParserError (message, buffer, offset) {\n  assert(buffer)\n  assert.strictEqual(typeof offset, 'number')\n\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n\n  const tmp = Error.stackTraceLimit\n  Error.stackTraceLimit = 2\n  Error.captureStackTrace(this, this.constructor)\n  Error.stackTraceLimit = tmp\n  this.offset = offset\n  this.buffer = buffer\n}\n\nutil.inherits(ParserError, RedisError)\n\nObject.defineProperty(ParserError.prototype, 'name', {\n  value: 'ParserError',\n  configurable: true,\n  writable: true\n})\n\n// ReplyError\n\nfunction ReplyError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  const tmp = Error.stackTraceLimit\n  Error.stackTraceLimit = 2\n  Error.captureStackTrace(this, this.constructor)\n  Error.stackTraceLimit = tmp\n}\n\nutil.inherits(ReplyError, RedisError)\n\nObject.defineProperty(ReplyError.prototype, 'name', {\n  value: 'ReplyError',\n  configurable: true,\n  writable: true\n})\n\n// AbortError\n\nfunction AbortError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  Error.captureStackTrace(this, this.constructor)\n}\n\nutil.inherits(AbortError, RedisError)\n\nObject.defineProperty(AbortError.prototype, 'name', {\n  value: 'AbortError',\n  configurable: true,\n  writable: true\n})\n\n// InterruptError\n\nfunction InterruptError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  Error.captureStackTrace(this, this.constructor)\n}\n\nutil.inherits(InterruptError, AbortError)\n\nObject.defineProperty(InterruptError.prototype, 'name', {\n  value: 'InterruptError',\n  configurable: true,\n  writable: true\n})\n\nmodule.exports = {\n  RedisError,\n  ParserError,\n  ReplyError,\n  AbortError,\n  InterruptError\n}\n","'use strict'\n\nconst assert = require('assert')\n\nclass RedisError extends Error {\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass ParserError extends RedisError {\n  constructor (message, buffer, offset) {\n    assert(buffer)\n    assert.strictEqual(typeof offset, 'number')\n\n    const tmp = Error.stackTraceLimit\n    Error.stackTraceLimit = 2\n    super(message)\n    Error.stackTraceLimit = tmp\n    this.offset = offset\n    this.buffer = buffer\n  }\n\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass ReplyError extends RedisError {\n  constructor (message) {\n    const tmp = Error.stackTraceLimit\n    Error.stackTraceLimit = 2\n    super(message)\n    Error.stackTraceLimit = tmp\n  }\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass AbortError extends RedisError {\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass InterruptError extends AbortError {\n  get name () {\n    return this.constructor.name\n  }\n}\n\nmodule.exports = {\n  RedisError,\n  ParserError,\n  ReplyError,\n  AbortError,\n  InterruptError\n}\n","'use strict'\n\nconst Errors = process.version.charCodeAt(1) < 55 && process.version.charCodeAt(2) === 46\n  ? require('./lib/old') // Node.js < 7\n  : require('./lib/modern')\n\nmodule.exports = Errors\n","/*\n * Copyright 2001-2010 Georges Menie (www.menie.org)\n * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style)\n * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript)\n * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc)\n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the University of California, Berkeley nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/* CRC16 implementation according to CCITT standards.\n *\n * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the\n * following parameters:\n *\n * Name                       : \"XMODEM\", also known as \"ZMODEM\", \"CRC-16/ACORN\"\n * Width                      : 16 bit\n * Poly                       : 1021 (That is actually x^16 + x^12 + x^5 + 1)\n * Initialization             : 0000\n * Reflect Input byte         : False\n * Reflect Output CRC         : False\n * Xor constant to output CRC : 0000\n * Output for \"123456789\"     : 31C3\n */\n\nvar lookup = [\n  0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,\n  0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,\n  0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,\n  0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,\n  0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,\n  0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,\n  0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,\n  0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,\n  0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,\n  0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,\n  0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,\n  0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,\n  0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,\n  0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,\n  0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,\n  0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,\n  0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,\n  0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,\n  0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,\n  0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,\n  0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,\n  0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,\n  0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,\n  0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,\n  0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,\n  0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,\n  0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,\n  0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,\n  0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,\n  0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,\n  0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,\n  0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0\n];\n\n/**\n * Convert a string to a UTF8 array - faster than via buffer\n * @param str\n * @returns {Array}\n */\nvar toUTF8Array = function toUTF8Array(str) {\n  var char;\n  var i = 0;\n  var p = 0;\n  var utf8 = [];\n  var len = str.length;\n\n  for (; i < len; i++) {\n    char = str.charCodeAt(i);\n    if (char < 128) {\n      utf8[p++] = char;\n    } else if (char < 2048) {\n      utf8[p++] = (char >> 6) | 192;\n      utf8[p++] = (char & 63) | 128;\n    } else if (\n        ((char & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n        ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n      char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);\n      utf8[p++] = (char >> 18) | 240;\n      utf8[p++] = ((char >> 12) & 63) | 128;\n      utf8[p++] = ((char >> 6) & 63) | 128;\n      utf8[p++] = (char & 63) | 128;\n    } else {\n      utf8[p++] = (char >> 12) | 224;\n      utf8[p++] = ((char >> 6) & 63) | 128;\n      utf8[p++] = (char & 63) | 128;\n    }\n  }\n\n  return utf8;\n};\n\n/**\n * Convert a string into a redis slot hash.\n * @param str\n * @returns {number}\n */\nvar generate = module.exports = function generate(str) {\n  var char;\n  var i = 0;\n  var start = -1;\n  var result = 0;\n  var resultHash = 0;\n  var utf8 = typeof str === 'string' ? toUTF8Array(str) : str;\n  var len = utf8.length;\n\n  while (i < len) {\n    char = utf8[i++];\n    if (start === -1) {\n      if (char === 0x7B) {\n        start = i;\n      }\n    } else if (char !== 0x7D) {\n      resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8);\n    } else if (i - 1 !== start) {\n      return resultHash & 0x3FFF;\n    }\n\n    result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8);\n  }\n\n  return result & 0x3FFF;\n};\n\n/**\n * Convert an array of multiple strings into a redis slot hash.\n * Returns -1 if one of the keys is not for the same slot as the others\n * @param keys\n * @returns {number}\n */\nmodule.exports.generateMulti = function generateMulti(keys) {\n  var i = 1;\n  var len = keys.length;\n  var base = generate(keys[0]);\n\n  while (i < len) {\n    if (generate(keys[i++]) !== base) return -1;\n  }\n\n  return base;\n};\n","\"use strict\";\n/*\n * Derived from `src/compat/object/defaults.ts` in es-toolkit\n * (https://github.com/toss/es-toolkit).\n *\n * Copyright (c) 2024 Viva Republica, Inc\n * Copyright OpenJS Foundation and other contributors\n *\n * Parts of the compatibility layer in `es-toolkit/compat` are derived from\n * Lodash (https://github.com/lodash/lodash) by the OpenJS Foundation\n * (https://openjsf.org/) and Underscore.js by Jeremy Ashkenas, DocumentCloud\n * and Investigative Reporters & Editors (http://underscorejs.org/).\n *\n * This file has been modified from the original source to create a standalone\n * adaptation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaults = void 0;\nconst IS_UNSIGNED_INTEGER = /^(?:0|[1-9]\\d*)$/;\nfunction isNil(value) {\n    return value == null;\n}\nfunction eq(value, other) {\n    return value === other || (Number.isNaN(value) && Number.isNaN(other));\n}\nfunction isLength(value) {\n    return Number.isSafeInteger(value) && value >= 0;\n}\nfunction isArrayLike(value) {\n    return (value != null &&\n        typeof value !== \"function\" &&\n        isLength(value.length));\n}\nfunction isObject(value) {\n    return (value !== null && (typeof value === \"object\" || typeof value === \"function\"));\n}\nfunction isIndex(value, length = Number.MAX_SAFE_INTEGER) {\n    switch (typeof value) {\n        case \"number\":\n            return Number.isInteger(value) && value >= 0 && value < length;\n        case \"symbol\":\n            return false;\n        case \"string\":\n            return IS_UNSIGNED_INTEGER.test(value);\n    }\n}\nfunction isIterateeCall(value, index, object) {\n    if (!isObject(object)) {\n        return false;\n    }\n    if ((typeof index === \"number\" &&\n        isArrayLike(object) &&\n        isIndex(index) &&\n        index < object.length) ||\n        (typeof index === \"string\" && index in object)) {\n        return eq(object[index], value);\n    }\n    return false;\n}\nfunction defaults(object, ...sources) {\n    object = Object(object);\n    const objectProto = Object.prototype;\n    let length = sources.length;\n    const guard = length > 2 ? sources[2] : undefined;\n    if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n        length = 1;\n    }\n    for (let i = 0; i < length; i++) {\n        if (isNil(sources[i])) {\n            continue;\n        }\n        const source = sources[i];\n        for (const key in source) {\n            const value = object[key];\n            if (value === undefined ||\n                (!objectProto.hasOwnProperty.call(object, key) &&\n                    eq(value, objectProto[key]))) {\n                object[key] = source[key];\n            }\n        }\n    }\n    return object;\n}\nexports.defaults = defaults;\n","\"use strict\";\n/*\n * Derived from `src/compat/predicate/isArguments.ts` in es-toolkit\n * (https://github.com/toss/es-toolkit).\n *\n * Copyright (c) 2024 Viva Republica, Inc\n * Copyright OpenJS Foundation and other contributors\n *\n * Parts of the compatibility layer in `es-toolkit/compat` are derived from\n * Lodash (https://github.com/lodash/lodash) by the OpenJS Foundation\n * (https://openjsf.org/) and Underscore.js by Jeremy Ashkenas, DocumentCloud\n * and Investigative Reporters & Editors (http://underscorejs.org/).\n *\n * This file has been modified from the original source to create a standalone\n * adaptation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isArguments = void 0;\nfunction getTag(value) {\n    if (value == null) {\n        return value === undefined ? \"[object Undefined]\" : \"[object Null]\";\n    }\n    return Object.prototype.toString.call(value);\n}\nfunction isArguments(value) {\n    return (value !== null &&\n        typeof value === \"object\" &&\n        getTag(value) === \"[object Arguments]\");\n}\nexports.isArguments = isArguments;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.noop = void 0;\nfunction noop() { }\nexports.noop = noop;\n__exportStar(require(\"./defaults\"), exports);\n__exportStar(require(\"./isArguments\"), exports);\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n *  - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n  options = options || {};\n  var type = typeof val;\n  if (type === 'string' && val.length > 0) {\n    return parse(val);\n  } else if (type === 'number' && isFinite(val)) {\n    return options.long ? fmtLong(val) : fmtShort(val);\n  }\n  throw new Error(\n    'val is not a non-empty string or a valid number. val=' +\n      JSON.stringify(val)\n  );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n  str = String(str);\n  if (str.length > 100) {\n    return;\n  }\n  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(\n    str\n  );\n  if (!match) {\n    return;\n  }\n  var n = parseFloat(match[1]);\n  var type = (match[2] || 'ms').toLowerCase();\n  switch (type) {\n    case 'years':\n    case 'year':\n    case 'yrs':\n    case 'yr':\n    case 'y':\n      return n * y;\n    case 'weeks':\n    case 'week':\n    case 'w':\n      return n * w;\n    case 'days':\n    case 'day':\n    case 'd':\n      return n * d;\n    case 'hours':\n    case 'hour':\n    case 'hrs':\n    case 'hr':\n    case 'h':\n      return n * h;\n    case 'minutes':\n    case 'minute':\n    case 'mins':\n    case 'min':\n    case 'm':\n      return n * m;\n    case 'seconds':\n    case 'second':\n    case 'secs':\n    case 'sec':\n    case 's':\n      return n * s;\n    case 'milliseconds':\n    case 'millisecond':\n    case 'msecs':\n    case 'msec':\n    case 'ms':\n      return n;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n  var msAbs = Math.abs(ms);\n  if (msAbs >= d) {\n    return Math.round(ms / d) + 'd';\n  }\n  if (msAbs >= h) {\n    return Math.round(ms / h) + 'h';\n  }\n  if (msAbs >= m) {\n    return Math.round(ms / m) + 'm';\n  }\n  if (msAbs >= s) {\n    return Math.round(ms / s) + 's';\n  }\n  return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n  var msAbs = Math.abs(ms);\n  if (msAbs >= d) {\n    return plural(ms, msAbs, d, 'day');\n  }\n  if (msAbs >= h) {\n    return plural(ms, msAbs, h, 'hour');\n  }\n  if (msAbs >= m) {\n    return plural(ms, msAbs, m, 'minute');\n  }\n  if (msAbs >= s) {\n    return plural(ms, msAbs, s, 'second');\n  }\n  return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n  var isPlural = msAbs >= n * 1.5;\n  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = `  ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.genRedactedString = exports.getStringValue = exports.MAX_ARGUMENT_LENGTH = void 0;\nconst debug_1 = require(\"debug\");\nconst MAX_ARGUMENT_LENGTH = 200;\nexports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH;\nconst NAMESPACE_PREFIX = \"ioredis\";\n/**\n * helper function that tried to get a string value for\n * arbitrary \"debug\" arg\n */\nfunction getStringValue(v) {\n    if (v === null) {\n        return;\n    }\n    switch (typeof v) {\n        case \"boolean\":\n            return;\n        case \"number\":\n            return;\n        case \"object\":\n            if (Buffer.isBuffer(v)) {\n                return v.toString(\"hex\");\n            }\n            if (Array.isArray(v)) {\n                return v.join(\",\");\n            }\n            try {\n                return JSON.stringify(v);\n            }\n            catch (e) {\n                return;\n            }\n        case \"string\":\n            return v;\n    }\n}\nexports.getStringValue = getStringValue;\n/**\n * helper function that redacts a string representation of a \"debug\" arg\n */\nfunction genRedactedString(str, maxLen) {\n    const { length } = str;\n    return length <= maxLen\n        ? str\n        : str.slice(0, maxLen) + ' ... <REDACTED full-length=\"' + length + '\">';\n}\nexports.genRedactedString = genRedactedString;\n/**\n * a wrapper for the `debug` module, used to generate\n * \"debug functions\" that trim the values in their output\n */\nfunction genDebugFunction(namespace) {\n    const fn = (0, debug_1.default)(`${NAMESPACE_PREFIX}:${namespace}`);\n    function wrappedDebug(...args) {\n        if (!fn.enabled) {\n            return; // no-op\n        }\n        // we skip the first arg because that is the message\n        for (let i = 1; i < args.length; i++) {\n            const str = getStringValue(args[i]);\n            if (typeof str === \"string\" && str.length > MAX_ARGUMENT_LENGTH) {\n                args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH);\n            }\n        }\n        return fn.apply(null, args);\n    }\n    Object.defineProperties(wrappedDebug, {\n        namespace: {\n            get() {\n                return fn.namespace;\n            },\n        },\n        enabled: {\n            get() {\n                return fn.enabled;\n            },\n        },\n        destroy: {\n            get() {\n                return fn.destroy;\n            },\n        },\n        log: {\n            get() {\n                return fn.log;\n            },\n            set(l) {\n                fn.log = l;\n            },\n        },\n    });\n    return wrappedDebug;\n}\nexports.default = genDebugFunction;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * TLS settings for Redis Cloud. Updated on 2022-08-19.\n */\nconst RedisCloudCA = `-----BEGIN CERTIFICATE-----\nMIIDTzCCAjegAwIBAgIJAKSVpiDswLcwMA0GCSqGSIb3DQEBBQUAMD4xFjAUBgNV\nBAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\ndGhvcml0eTAeFw0xMzEwMDExMjE0NTVaFw0yMzA5MjkxMjE0NTVaMD4xFjAUBgNV\nBAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\ndGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALZqkh/DczWP\nJnxnHLQ7QL0T4B4CDKWBKCcisriGbA6ZePWVNo4hfKQC6JrzfR+081NeD6VcWUiz\nrmd+jtPhIY4c+WVQYm5PKaN6DT1imYdxQw7aqO5j2KUCEh/cznpLxeSHoTxlR34E\nQwF28Wl3eg2vc5ct8LjU3eozWVk3gb7alx9mSA2SgmuX5lEQawl++rSjsBStemY2\nBDwOpAMXIrdEyP/cVn8mkvi/BDs5M5G+09j0gfhyCzRWMQ7Hn71u1eolRxwVxgi3\nTMn+/vTaFSqxKjgck6zuAYjBRPaHe7qLxHNr1So/Mc9nPy+3wHebFwbIcnUojwbp\n4nctkWbjb2cCAwEAAaNQME4wHQYDVR0OBBYEFP1whtcrydmW3ZJeuSoKZIKjze3w\nMB8GA1UdIwQYMBaAFP1whtcrydmW3ZJeuSoKZIKjze3wMAwGA1UdEwQFMAMBAf8w\nDQYJKoZIhvcNAQEFBQADggEBAG2erXhwRAa7+ZOBs0B6X57Hwyd1R4kfmXcs0rta\nlbPpvgULSiB+TCbf3EbhJnHGyvdCY1tvlffLjdA7HJ0P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CloudFixed: { ca: RedisCloudCA },\n    RedisCloudFlexible: { ca: RedisCloudCA },\n};\nexports.default = TLSProfiles;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.noop = exports.isArguments = exports.defaults = exports.Debug = exports.getPackageMeta = exports.zipMap = exports.CONNECTION_CLOSED_ERROR_MSG = exports.shuffle = exports.sample = exports.resolveTLSProfile = exports.parseURL = exports.optimizeErrorStack = exports.toArg = exports.convertMapToArray = exports.convertObjectToArray = exports.timeout = exports.packObject = exports.isInt = exports.wrapMultiResult = exports.convertBufferToString = void 0;\nconst fs_1 = require(\"fs\");\nconst path_1 = require(\"path\");\nconst lodash_1 = require(\"./lodash\");\nObject.defineProperty(exports, \"defaults\", { enumerable: true, get: function () { return lodash_1.defaults; } });\nObject.defineProperty(exports, \"isArguments\", { enumerable: true, get: function () { return lodash_1.isArguments; } });\nObject.defineProperty(exports, \"noop\", { enumerable: true, get: function () { return lodash_1.noop; } });\nconst debug_1 = require(\"./debug\");\nexports.Debug = debug_1.default;\nconst TLSProfiles_1 = require(\"../constants/TLSProfiles\");\n/**\n * Convert a buffer to string, supports buffer array\n *\n * @example\n * ```js\n * const input = [Buffer.from('foo'), [Buffer.from('bar')]]\n * const res = convertBufferToString(input, 'utf8')\n * expect(res).to.eql(['foo', ['bar']])\n * ```\n */\nfunction convertBufferToString(value, encoding) {\n    if (value instanceof Buffer) {\n        return value.toString(encoding);\n    }\n    if (Array.isArray(value)) {\n        const length = value.length;\n        const res = Array(length);\n        for (let i = 0; i < length; ++i) {\n            res[i] =\n                value[i] instanceof Buffer && encoding === \"utf8\"\n                    ? value[i].toString()\n                    : convertBufferToString(value[i], encoding);\n        }\n        return res;\n    }\n    return value;\n}\nexports.convertBufferToString = convertBufferToString;\n/**\n * Convert a list of results to node-style\n *\n * @example\n * ```js\n * const input = ['a', 'b', new Error('c'), 'd']\n * const output = exports.wrapMultiResult(input)\n * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd'])\n * ```\n */\nfunction wrapMultiResult(arr) {\n    // When using WATCH/EXEC transactions, the EXEC will return\n    // a null instead of an array\n    if (!arr) {\n        return null;\n    }\n    const result = [];\n    const length = arr.length;\n    for (let i = 0; i < length; ++i) {\n        const item = arr[i];\n        if (item instanceof Error) {\n            result.push([item]);\n        }\n        else {\n            result.push([null, item]);\n        }\n    }\n    return result;\n}\nexports.wrapMultiResult = wrapMultiResult;\n/**\n * Detect if the argument is a int\n * @example\n * ```js\n * > isInt('123')\n * true\n * > isInt('123.3')\n * false\n * > isInt('1x')\n * false\n * > isInt(123)\n * true\n * > isInt(true)\n * false\n * ```\n */\nfunction isInt(value) {\n    const x = parseFloat(value);\n    return !isNaN(value) && (x | 0) === x;\n}\nexports.isInt = isInt;\n/**\n * Pack an array to an Object\n *\n * @example\n * ```js\n * > packObject(['a', 'b', 'c', 'd'])\n * { a: 'b', c: 'd' }\n * ```\n */\nfunction packObject(array) {\n    const result = {};\n    const length = array.length;\n    for (let i = 1; i < length; i += 2) {\n        result[array[i - 1]] = array[i];\n    }\n    return result;\n}\nexports.packObject = packObject;\n/**\n * Return a callback with timeout\n */\nfunction timeout(callback, timeout) {\n    let timer = null;\n    const run = function () {\n        if (timer) {\n            clearTimeout(timer);\n            timer = null;\n            callback.apply(this, arguments);\n        }\n    };\n    timer = setTimeout(run, timeout, new Error(\"timeout\"));\n    return run;\n}\nexports.timeout = timeout;\n/**\n * Convert an object to an array\n * @example\n * ```js\n * > convertObjectToArray({ a: '1' })\n * ['a', '1']\n * ```\n */\nfunction convertObjectToArray(obj) {\n    const result = [];\n    const keys = Object.keys(obj); // Object.entries requires node 7+\n    for (let i = 0, l = keys.length; i < l; i++) {\n        result.push(keys[i], obj[keys[i]]);\n    }\n    return result;\n}\nexports.convertObjectToArray = convertObjectToArray;\n/**\n * Convert a map to an array\n * @example\n * ```js\n * > convertMapToArray(new Map([[1, '2']]))\n * [1, '2']\n * ```\n */\nfunction convertMapToArray(map) {\n    const result = [];\n    let pos = 0;\n    map.forEach(function (value, key) {\n        result[pos] = key;\n        result[pos + 1] = value;\n        pos += 2;\n    });\n    return result;\n}\nexports.convertMapToArray = convertMapToArray;\n/**\n * Convert a non-string arg to a string\n */\nfunction toArg(arg) {\n    if (arg === null || typeof arg === \"undefined\") {\n        return \"\";\n    }\n    return String(arg);\n}\nexports.toArg = toArg;\n/**\n * Optimize error stack\n *\n * @param error actually error\n * @param friendlyStack the stack that more meaningful\n * @param filterPath only show stacks with the specified path\n */\nfunction optimizeErrorStack(error, friendlyStack, filterPath) {\n    const stacks = friendlyStack.split(\"\\n\");\n    let lines = \"\";\n    let i;\n    for (i = 1; i < stacks.length; ++i) {\n        if (stacks[i].indexOf(filterPath) === -1) {\n            break;\n        }\n    }\n    for (let j = i; j < stacks.length; ++j) {\n        lines += \"\\n\" + stacks[j];\n    }\n    if (error.stack) {\n        const pos = error.stack.indexOf(\"\\n\");\n        error.stack = error.stack.slice(0, pos) + lines;\n    }\n    return error;\n}\nexports.optimizeErrorStack = optimizeErrorStack;\n/**\n * Parse the redis protocol url\n */\nfunction parseURL(url) {\n    if (isInt(url)) {\n        return { port: url };\n    }\n    // Re-assert string type: isInt's type guard (value is string) incorrectly\n    // narrows url to 'never' in the false branch since url is already string.\n    const rawUrl = url;\n    // Determine if the URL has a known protocol (redis:// or rediss://)\n    const hasProtocol = /^rediss?:\\/\\//i.test(rawUrl);\n    const isProtocolRelative = rawUrl.startsWith(\"//\");\n    // TODO(next major): Consider rejecting protocol-relative Redis URLs early and\n    // requiring explicit redis:// or rediss:// schemes instead. Keep them working\n    // in 5.x for backward compatibility.\n    // Unix socket paths (starting with \"/\") are not valid URLs — handle separately.\n    // Preserve query params (e.g., /tmp/redis.sock?db=2)\n    if (rawUrl[0] === \"/\" && !isProtocolRelative) {\n        const qIdx = rawUrl.indexOf(\"?\");\n        const result = {\n            path: qIdx === -1 ? rawUrl : rawUrl.slice(0, qIdx),\n        };\n        if (qIdx !== -1) {\n            const options = {};\n            const params = new URLSearchParams(rawUrl.slice(qIdx + 1));\n            params.forEach((value, key) => {\n                options[key] = parseURLQueryItem(key, value);\n            });\n            (0, lodash_1.defaults)(result, options);\n        }\n        return result;\n    }\n    let parsed;\n    if (hasProtocol) {\n        parsed = new URL(rawUrl);\n    }\n    else if (isProtocolRelative) {\n        parsed = new URL(\"redis:\" + rawUrl);\n    }\n    else {\n        // Prepend a dummy protocol so new URL() can parse \"host:port?query\" correctly\n        parsed = new URL(\"redis://\" + rawUrl);\n    }\n    // Convert searchParams to a plain object (equivalent to url.parse(url, true).query)\n    const options = {};\n    parsed.searchParams.forEach((value, key) => {\n        options[key] = parseURLQueryItem(key, value);\n    });\n    const result = {};\n    // Extract auth — WHATWG URL percent-encodes special chars, so decode them.\n    // Check both username AND password: redis://:password@host has empty username but valid password.\n    if (parsed.username || parsed.password) {\n        result.username = decodeURIComponent(parsed.username);\n        result.password = decodeURIComponent(parsed.password);\n    }\n    if (parsed.pathname && parsed.pathname !== \"/\") {\n        if (hasProtocol || isProtocolRelative) {\n            // For redis://, rediss://, and protocol-relative URLs, the path after /\n            // is the db number\n            if (parsed.pathname.length > 1) {\n                result.db = parsed.pathname.slice(1);\n            }\n        }\n        else {\n            result.path = parsed.pathname;\n        }\n    }\n    if (parsed.hostname) {\n        // WHATWG URL keeps brackets around IPv6 addresses (e.g., \"[::1]\").\n        // Strip them to match the old url.parse() behavior.\n        result.host = parsed.hostname.replace(/^\\[|\\]$/g, \"\");\n    }\n    if (parsed.port) {\n        result.port = parsed.port;\n    }\n    (0, lodash_1.defaults)(result, options);\n    return result;\n}\nexports.parseURL = parseURL;\nfunction parseURLQueryItem(key, value) {\n    if (key === \"family\") {\n        const intFamily = Number.parseInt(value, 10);\n        if (!Number.isNaN(intFamily)) {\n            return intFamily;\n        }\n    }\n    return value;\n}\n/**\n * Resolve TLS profile shortcut in connection options\n */\nfunction resolveTLSProfile(options) {\n    let tls = options === null || options === void 0 ? void 0 : options.tls;\n    if (typeof tls === \"string\")\n        tls = { profile: tls };\n    const profile = TLSProfiles_1.default[tls === null || tls === void 0 ? void 0 : tls.profile];\n    if (profile) {\n        tls = Object.assign({}, profile, tls);\n        delete tls.profile;\n        options = Object.assign({}, options, { tls });\n    }\n    return options;\n}\nexports.resolveTLSProfile = resolveTLSProfile;\n/**\n * Get a random element from `array`\n */\nfunction sample(array, from = 0) {\n    const length = array.length;\n    if (from >= length) {\n        return null;\n    }\n    return array[from + Math.floor(Math.random() * (length - from))];\n}\nexports.sample = sample;\n/**\n * Shuffle the array using the Fisher-Yates Shuffle.\n * This method will mutate the original array.\n */\nfunction shuffle(array) {\n    let counter = array.length;\n    // While there are elements in the array\n    while (counter > 0) {\n        // Pick a random index\n        const index = Math.floor(Math.random() * counter);\n        // Decrease counter by 1\n        counter--;\n        // And swap the last element with it\n        [array[counter], array[index]] = [array[index], array[counter]];\n    }\n    return array;\n}\nexports.shuffle = shuffle;\n/**\n * Error message for connection being disconnected\n */\nexports.CONNECTION_CLOSED_ERROR_MSG = \"Connection is closed.\";\nfunction zipMap(keys, values) {\n    const map = new Map();\n    keys.forEach((key, index) => {\n        map.set(key, values[index]);\n    });\n    return map;\n}\nexports.zipMap = zipMap;\n/**\n * Memoized package metadata to avoid repeated file system reads.\n *\n * @internal\n */\nlet cachedPackageMeta = null;\n/**\n * Retrieves cached package metadata from package.json.\n *\n * @internal\n * @returns {Promise<{version: string} | null>} Package metadata or null if unavailable\n */\nasync function getPackageMeta() {\n    if (cachedPackageMeta) {\n        return cachedPackageMeta;\n    }\n    try {\n        const filePath = (0, path_1.resolve)(__dirname, \"..\", \"..\", \"package.json\");\n        const data = await fs_1.promises.readFile(filePath, \"utf8\");\n        const parsed = JSON.parse(data);\n        cachedPackageMeta = {\n            version: parsed.version,\n        };\n        return cachedPackageMeta;\n    }\n    catch (err) {\n        cachedPackageMeta = {\n            version: \"error-fetching-version\",\n        };\n        return cachedPackageMeta;\n    }\n}\nexports.getPackageMeta = getPackageMeta;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parseBlockOption = exports.parseSecondsArgument = void 0;\n/**\n * Parses a command parameter to a number.\n * @param arg - The command parameter to parse (number, string, or Buffer)\n * @returns The parsed number, or undefined if parsing fails or arg is undefined\n */\nconst parseNumberArgument = (arg) => {\n    if (typeof arg === \"number\") {\n        return arg;\n    }\n    if (Buffer.isBuffer(arg)) {\n        return parseNumberArgument(arg.toString());\n    }\n    if (typeof arg === \"string\") {\n        const value = Number(arg);\n        return Number.isFinite(value) ? value : undefined;\n    }\n    return undefined;\n};\n/**\n * Parses a command parameter to a string.\n * @param arg - The command parameter to parse (string or Buffer)\n * @returns The parsed string, or undefined if arg is not a string/Buffer or is undefined\n */\nconst parseStringArgument = (arg) => {\n    if (typeof arg === \"string\") {\n        return arg;\n    }\n    if (Buffer.isBuffer(arg)) {\n        return arg.toString();\n    }\n    return undefined;\n};\n/**\n * Parses a command parameter as seconds and converts to milliseconds.\n * @param arg - The command parameter representing seconds\n * @returns The value in milliseconds, 0 if value is <= 0, or undefined if parsing fails\n */\nconst parseSecondsArgument = (arg) => {\n    const value = parseNumberArgument(arg);\n    if (value === undefined) {\n        return undefined;\n    }\n    if (value <= 0) {\n        return 0;\n    }\n    return value * 1000;\n};\nexports.parseSecondsArgument = parseSecondsArgument;\n/**\n * Parses the BLOCK option from Redis command arguments (e.g., XREAD, XREADGROUP).\n * @param args - Array of command parameters to search for the BLOCK option\n * @returns The block duration in milliseconds, 0 if duration is <= 0,\n *          null if BLOCK option is not found, or undefined if BLOCK is found but duration is invalid\n */\nconst parseBlockOption = (args) => {\n    for (let i = 0; i < args.length; i++) {\n        const token = parseStringArgument(args[i]);\n        if (token && token.toLowerCase() === \"block\") {\n            const duration = parseNumberArgument(args[i + 1]);\n            if (duration === undefined) {\n                return undefined;\n            }\n            if (duration <= 0) {\n                return 0;\n            }\n            return duration;\n        }\n    }\n    return null;\n};\nexports.parseBlockOption = parseBlockOption;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst calculateSlot = require(\"cluster-key-slot\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst utils_1 = require(\"./utils\");\nconst argumentParsers_1 = require(\"./utils/argumentParsers\");\n/**\n * Command instance\n *\n * It's rare that you need to create a Command instance yourself.\n *\n * ```js\n * var infoCommand = new Command('info', null, function (err, result) {\n *   console.log('result', result);\n * });\n *\n * redis.sendCommand(infoCommand);\n *\n * // When no callback provided, Command instance will have a `promise` property,\n * // which will resolve/reject with the result of the command.\n * var getCommand = new Command('get', ['foo']);\n * getCommand.promise.then(function (result) {\n *   console.log('result', result);\n * });\n * ```\n */\nclass Command {\n    /**\n     * Creates an instance of Command.\n     * @param name Command name\n     * @param args An array of command arguments\n     * @param options\n     * @param callback The callback that handles the response.\n     * If omit, the response will be handled via Promise\n     */\n    constructor(name, args = [], options = {}, callback) {\n        this.name = name;\n        this.inTransaction = false;\n        this.isTraced = false;\n        this.isResolved = false;\n        this.transformed = false;\n        this.replyEncoding = options.replyEncoding;\n        this.errorStack = options.errorStack;\n        this.args = args.flat();\n        this.callback = callback;\n        this.initPromise();\n        if (options.keyPrefix) {\n            // @ts-expect-error\n            const isBufferKeyPrefix = options.keyPrefix instanceof Buffer;\n            // @ts-expect-error\n            let keyPrefixBuffer = isBufferKeyPrefix\n                ? options.keyPrefix\n                : null;\n            this._iterateKeys((key) => {\n                if (key instanceof Buffer) {\n                    if (keyPrefixBuffer === null) {\n                        keyPrefixBuffer = Buffer.from(options.keyPrefix);\n                    }\n                    return Buffer.concat([keyPrefixBuffer, key]);\n                }\n                else if (isBufferKeyPrefix) {\n                    // @ts-expect-error\n                    return Buffer.concat([options.keyPrefix, Buffer.from(String(key))]);\n                }\n                return options.keyPrefix + key;\n            });\n        }\n        if (options.readOnly) {\n            this.isReadOnly = true;\n        }\n    }\n    /**\n     * Check whether the command has the flag\n     */\n    static checkFlag(flagName, commandName) {\n        commandName = commandName.toLowerCase();\n        return !!this.getFlagMap()[flagName][commandName];\n    }\n    static setArgumentTransformer(name, func) {\n        this._transformer.argument[name] = func;\n    }\n    static setReplyTransformer(name, func) {\n        this._transformer.reply[name] = func;\n    }\n    static getFlagMap() {\n        if (!this.flagMap) {\n            this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => {\n                map[flagName] = {};\n                Command.FLAGS[flagName].forEach((commandName) => {\n                    map[flagName][commandName] = true;\n                });\n                return map;\n            }, {});\n        }\n        return this.flagMap;\n    }\n    getSlot() {\n        if (typeof this.slot === \"undefined\") {\n            const key = this.getKeys()[0];\n            this.slot = key == null ? null : calculateSlot(key);\n        }\n        return this.slot;\n    }\n    getKeys() {\n        return this._iterateKeys();\n    }\n    /**\n     * Convert command to writable buffer or string\n     */\n    toWritable(_socket) {\n        let result;\n        const commandStr = \"*\" +\n            (this.args.length + 1) +\n            \"\\r\\n$\" +\n            Buffer.byteLength(this.name) +\n            \"\\r\\n\" +\n            this.name +\n            \"\\r\\n\";\n        if (this.bufferMode) {\n            const buffers = new MixedBuffers();\n            buffers.push(commandStr);\n            for (let i = 0; i < this.args.length; ++i) {\n                const arg = this.args[i];\n                if (arg instanceof Buffer) {\n                    if (arg.length === 0) {\n                        buffers.push(\"$0\\r\\n\\r\\n\");\n                    }\n                    else {\n                        buffers.push(\"$\" + arg.length + \"\\r\\n\");\n                        buffers.push(arg);\n                        buffers.push(\"\\r\\n\");\n                    }\n                }\n                else {\n                    buffers.push(\"$\" +\n                        Buffer.byteLength(arg) +\n                        \"\\r\\n\" +\n                        arg +\n                        \"\\r\\n\");\n                }\n            }\n            result = buffers.toBuffer();\n        }\n        else {\n            result = commandStr;\n            for (let i = 0; i < this.args.length; ++i) {\n                const arg = this.args[i];\n                result +=\n                    \"$\" +\n                        Buffer.byteLength(arg) +\n                        \"\\r\\n\" +\n                        arg +\n                        \"\\r\\n\";\n            }\n        }\n        return result;\n    }\n    stringifyArguments() {\n        for (let i = 0; i < this.args.length; ++i) {\n            const arg = this.args[i];\n            if (typeof arg === \"string\") {\n                // buffers and strings don't need any transformation\n            }\n            else if (arg instanceof Buffer) {\n                this.bufferMode = true;\n            }\n            else {\n                this.args[i] = (0, utils_1.toArg)(arg);\n            }\n        }\n    }\n    /**\n     * Convert buffer/buffer[] to string/string[],\n     * and apply reply transformer.\n     */\n    transformReply(result) {\n        if (this.replyEncoding) {\n            result = (0, utils_1.convertBufferToString)(result, this.replyEncoding);\n        }\n        const transformer = Command._transformer.reply[this.name];\n        if (transformer) {\n            result = transformer(result);\n        }\n        return result;\n    }\n    /**\n     * Set the wait time before terminating the attempt to execute a command\n     * and generating an error.\n     */\n    setTimeout(ms) {\n        if (!this._commandTimeoutTimer) {\n            this._commandTimeoutTimer = setTimeout(() => {\n                if (!this.isResolved) {\n                    this.reject(new Error(\"Command timed out\"));\n                }\n            }, ms);\n        }\n    }\n    /**\n     * Set a timeout for blocking commands.\n     * When the timeout expires, the command resolves with null (matching Redis behavior).\n     * This handles the case of undetectable network failures (e.g., docker network disconnect)\n     * where the TCP connection becomes a zombie and no close event fires.\n     */\n    setBlockingTimeout(ms) {\n        if (ms <= 0) {\n            return;\n        }\n        // Clear existing timer if any (can happen when command moves from offline to command queue)\n        if (this._blockingTimeoutTimer) {\n            clearTimeout(this._blockingTimeoutTimer);\n            this._blockingTimeoutTimer = undefined;\n        }\n        const now = Date.now();\n        // First call: establish absolute deadline\n        if (this._blockingDeadline === undefined) {\n            this._blockingDeadline = now + ms;\n        }\n        // Check if we've already exceeded the deadline\n        const remaining = this._blockingDeadline - now;\n        if (remaining <= 0) {\n            // Resolve with null to indicate timeout (same as Redis behavior)\n            this.resolve(null);\n            return;\n        }\n        this._blockingTimeoutTimer = setTimeout(() => {\n            if (this.isResolved) {\n                this._blockingTimeoutTimer = undefined;\n                return;\n            }\n            this._blockingTimeoutTimer = undefined;\n            // Timeout expired - resolve with null (same as Redis behavior when blocking command times out)\n            this.resolve(null);\n        }, remaining);\n    }\n    /**\n     * Extract the blocking timeout from the command arguments.\n     *\n     * @returns The timeout in seconds, null for indefinite blocking (timeout of 0),\n     *          or undefined if this is not a blocking command\n     */\n    extractBlockingTimeout() {\n        const args = this.args;\n        if (!args || args.length === 0) {\n            return undefined;\n        }\n        const name = this.name.toLowerCase();\n        if (Command.checkFlag(\"LAST_ARG_TIMEOUT_COMMANDS\", name)) {\n            return (0, argumentParsers_1.parseSecondsArgument)(args[args.length - 1]);\n        }\n        if (Command.checkFlag(\"FIRST_ARG_TIMEOUT_COMMANDS\", name)) {\n            return (0, argumentParsers_1.parseSecondsArgument)(args[0]);\n        }\n        if (Command.checkFlag(\"BLOCK_OPTION_COMMANDS\", name)) {\n            return (0, argumentParsers_1.parseBlockOption)(args);\n        }\n        return undefined;\n    }\n    /**\n     * Clear the command and blocking timers\n     */\n    _clearTimers() {\n        const existingTimer = this._commandTimeoutTimer;\n        if (existingTimer) {\n            clearTimeout(existingTimer);\n            delete this._commandTimeoutTimer;\n        }\n        const blockingTimer = this._blockingTimeoutTimer;\n        if (blockingTimer) {\n            clearTimeout(blockingTimer);\n            delete this._blockingTimeoutTimer;\n        }\n    }\n    initPromise() {\n        const promise = new Promise((resolve, reject) => {\n            if (!this.transformed) {\n                this.transformed = true;\n                const transformer = Command._transformer.argument[this.name];\n                if (transformer) {\n                    this.args = transformer(this.args);\n                }\n                this.stringifyArguments();\n            }\n            this.resolve = this._convertValue(resolve);\n            this.reject = (err) => {\n                this._clearTimers();\n                if (this.errorStack) {\n                    reject((0, utils_1.optimizeErrorStack)(err, this.errorStack.stack, __dirname));\n                }\n                else {\n                    reject(err);\n                }\n            };\n        });\n        this.promise = (0, standard_as_callback_1.default)(promise, this.callback);\n    }\n    /**\n     * Iterate through the command arguments that are considered keys.\n     */\n    _iterateKeys(transform = (key) => key) {\n        if (typeof this.keys === \"undefined\") {\n            this.keys = [];\n            if ((0, commands_1.exists)(this.name, { caseInsensitive: true })) {\n                // @ts-expect-error\n                const keyIndexes = (0, commands_1.getKeyIndexes)(this.name, this.args, {\n                    nameCaseInsensitive: true,\n                });\n                for (const index of keyIndexes) {\n                    this.args[index] = transform(this.args[index]);\n                    this.keys.push(this.args[index]);\n                }\n            }\n        }\n        return this.keys;\n    }\n    /**\n     * Convert the value from buffer to the target encoding.\n     */\n    _convertValue(resolve) {\n        return (value) => {\n            try {\n                this._clearTimers();\n                resolve(this.transformReply(value));\n                this.isResolved = true;\n            }\n            catch (err) {\n                this.reject(err);\n            }\n            return this.promise;\n        };\n    }\n}\nexports.default = Command;\nCommand.FLAGS = {\n    VALID_IN_SUBSCRIBER_MODE: [\n        \"subscribe\",\n        \"psubscribe\",\n        \"unsubscribe\",\n        \"punsubscribe\",\n        \"ssubscribe\",\n        \"sunsubscribe\",\n        \"ping\",\n        \"quit\",\n    ],\n    VALID_IN_MONITOR_MODE: [\"monitor\", \"auth\"],\n    ENTER_SUBSCRIBER_MODE: [\"subscribe\", \"psubscribe\", \"ssubscribe\"],\n    EXIT_SUBSCRIBER_MODE: [\"unsubscribe\", \"punsubscribe\", \"sunsubscribe\"],\n    WILL_DISCONNECT: [\"quit\"],\n    HANDSHAKE_COMMANDS: [\"auth\", \"select\", \"client\", \"readonly\", \"info\"],\n    IGNORE_RECONNECT_ON_ERROR: [\"client\"],\n    BLOCKING_COMMANDS: [\n        \"blpop\",\n        \"brpop\",\n        \"brpoplpush\",\n        \"blmove\",\n        \"bzpopmin\",\n        \"bzpopmax\",\n        \"bzmpop\",\n        \"blmpop\",\n        \"xread\",\n        \"xreadgroup\",\n    ],\n    LAST_ARG_TIMEOUT_COMMANDS: [\n        \"blpop\",\n        \"brpop\",\n        \"brpoplpush\",\n        \"blmove\",\n        \"bzpopmin\",\n        \"bzpopmax\",\n    ],\n    FIRST_ARG_TIMEOUT_COMMANDS: [\"bzmpop\", \"blmpop\"],\n    BLOCK_OPTION_COMMANDS: [\"xread\", \"xreadgroup\"],\n};\nCommand._transformer = {\n    argument: {},\n    reply: {},\n};\nconst msetArgumentTransformer = function (args) {\n    if (args.length === 1) {\n        if (args[0] instanceof Map) {\n            return (0, utils_1.convertMapToArray)(args[0]);\n        }\n        if (typeof args[0] === \"object\" && args[0] !== null) {\n            return (0, utils_1.convertObjectToArray)(args[0]);\n        }\n    }\n    return args;\n};\nconst hsetArgumentTransformer = function (args) {\n    if (args.length === 2) {\n        if (args[1] instanceof Map) {\n            return [args[0]].concat((0, utils_1.convertMapToArray)(args[1]));\n        }\n        if (typeof args[1] === \"object\" && args[1] !== null) {\n            return [args[0]].concat((0, utils_1.convertObjectToArray)(args[1]));\n        }\n    }\n    return args;\n};\nCommand.setArgumentTransformer(\"mset\", msetArgumentTransformer);\nCommand.setArgumentTransformer(\"msetnx\", msetArgumentTransformer);\nCommand.setArgumentTransformer(\"hset\", hsetArgumentTransformer);\nCommand.setArgumentTransformer(\"hmset\", hsetArgumentTransformer);\nCommand.setReplyTransformer(\"hgetall\", function (result) {\n    if (Array.isArray(result)) {\n        const obj = {};\n        for (let i = 0; i < result.length; i += 2) {\n            const key = result[i];\n            const value = result[i + 1];\n            if (key in obj) {\n                // can only be truthy if the property is special somehow, like '__proto__' or 'constructor'\n                // https://github.com/luin/ioredis/issues/1267\n                Object.defineProperty(obj, key, {\n                    value,\n                    configurable: true,\n                    enumerable: true,\n                    writable: true,\n                });\n            }\n            else {\n                obj[key] = value;\n            }\n        }\n        return obj;\n    }\n    return result;\n});\nclass MixedBuffers {\n    constructor() {\n        this.length = 0;\n        this.items = [];\n    }\n    push(x) {\n        this.length += Buffer.byteLength(x);\n        this.items.push(x);\n    }\n    toBuffer() {\n        const result = Buffer.allocUnsafe(this.length);\n        let offset = 0;\n        for (const item of this.items) {\n            const length = Buffer.byteLength(item);\n            Buffer.isBuffer(item)\n                ? item.copy(result, offset)\n                : result.write(item, offset, length);\n            offset += length;\n        }\n        return result;\n    }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst redis_errors_1 = require(\"redis-errors\");\nclass ClusterAllFailedError extends redis_errors_1.RedisError {\n    constructor(message, lastNodeError) {\n        super(message);\n        this.lastNodeError = lastNodeError;\n        Error.captureStackTrace(this, this.constructor);\n    }\n    get name() {\n        return this.constructor.name;\n    }\n}\nexports.default = ClusterAllFailedError;\nClusterAllFailedError.defaultMessage = \"Failed to refresh slots cache.\";\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst stream_1 = require(\"stream\");\n/**\n * Convenient class to convert the process of scanning keys to a readable stream.\n */\nclass ScanStream extends stream_1.Readable {\n    constructor(opt) {\n        super(opt);\n        this.opt = opt;\n        this._redisCursor = \"0\";\n        this._redisDrained = false;\n    }\n    _read() {\n        if (this._redisDrained) {\n            this.push(null);\n            return;\n        }\n        const args = [this._redisCursor];\n        if (this.opt.key) {\n            args.unshift(this.opt.key);\n        }\n        if (this.opt.match) {\n            args.push(\"MATCH\", this.opt.match);\n        }\n        if (this.opt.type) {\n            args.push(\"TYPE\", this.opt.type);\n        }\n        if (this.opt.count) {\n            args.push(\"COUNT\", String(this.opt.count));\n        }\n        if (this.opt.noValues) {\n            args.push(\"NOVALUES\");\n        }\n        this.opt.redis[this.opt.command](args, (err, res) => {\n            if (err) {\n                this.emit(\"error\", err);\n                return;\n            }\n            this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0];\n            if (this._redisCursor === \"0\") {\n                this._redisDrained = true;\n            }\n            this.push(res[1]);\n        });\n    }\n    close() {\n        this._redisDrained = true;\n    }\n}\nexports.default = ScanStream;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.executeWithAutoPipelining = exports.getFirstValueInFlattenedArray = exports.shouldUseAutoPipelining = exports.notAllowedAutoPipelineCommands = exports.kCallbacks = exports.kExec = void 0;\nconst lodash_1 = require(\"./utils/lodash\");\nconst calculateSlot = require(\"cluster-key-slot\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst commands_1 = require(\"@ioredis/commands\");\nexports.kExec = Symbol(\"exec\");\nexports.kCallbacks = Symbol(\"callbacks\");\nexports.notAllowedAutoPipelineCommands = [\n    \"auth\",\n    \"info\",\n    \"script\",\n    \"quit\",\n    \"cluster\",\n    \"pipeline\",\n    \"multi\",\n    \"subscribe\",\n    \"psubscribe\",\n    \"unsubscribe\",\n    \"unpsubscribe\",\n    \"select\",\n    \"client\",\n];\nfunction executeAutoPipeline(client, slotKey) {\n    /*\n      If a pipeline is already executing, keep queueing up commands\n      since ioredis won't serve two pipelines at the same time\n    */\n    if (client._runningAutoPipelines.has(slotKey)) {\n        return;\n    }\n    if (!client._autoPipelines.has(slotKey)) {\n        /*\n          Rare edge case. Somehow, something has deleted this running autopipeline in an immediate\n          call to executeAutoPipeline.\n         \n          Maybe the callback in the pipeline.exec is sometimes called in the same tick,\n          e.g. if redis is disconnected?\n        */\n        return;\n    }\n    client._runningAutoPipelines.add(slotKey);\n    // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline\n    const pipeline = client._autoPipelines.get(slotKey);\n    client._autoPipelines.delete(slotKey);\n    const callbacks = pipeline[exports.kCallbacks];\n    // Stop keeping a reference to callbacks immediately after the callbacks stop being used.\n    // This allows the GC to reclaim objects referenced by callbacks, especially with 16384 slots\n    // in Redis.Cluster\n    pipeline[exports.kCallbacks] = null;\n    // Perform the call\n    pipeline.exec(function (err, results) {\n        client._runningAutoPipelines.delete(slotKey);\n        /*\n          Invoke all callback in nextTick so the stack is cleared\n          and callbacks can throw errors without affecting other callbacks.\n        */\n        if (err) {\n            for (let i = 0; i < callbacks.length; i++) {\n                process.nextTick(callbacks[i], err);\n            }\n        }\n        else {\n            for (let i = 0; i < callbacks.length; i++) {\n                process.nextTick(callbacks[i], ...results[i]);\n            }\n        }\n        // If there is another pipeline on the same node, immediately execute it without waiting for nextTick\n        if (client._autoPipelines.has(slotKey)) {\n            executeAutoPipeline(client, slotKey);\n        }\n    });\n}\nfunction shouldUseAutoPipelining(client, functionName, commandName) {\n    return (functionName &&\n        client.options.enableAutoPipelining &&\n        !client.isPipeline &&\n        !exports.notAllowedAutoPipelineCommands.includes(commandName) &&\n        !client.options.autoPipeliningIgnoredCommands.includes(commandName));\n}\nexports.shouldUseAutoPipelining = shouldUseAutoPipelining;\nfunction getFirstValueInFlattenedArray(args) {\n    for (let i = 0; i < args.length; i++) {\n        const arg = args[i];\n        if (typeof arg === \"string\") {\n            return arg;\n        }\n        else if (Array.isArray(arg) || (0, lodash_1.isArguments)(arg)) {\n            if (arg.length === 0) {\n                continue;\n            }\n            return arg[0];\n        }\n        const flattened = [arg].flat();\n        if (flattened.length > 0) {\n            return flattened[0];\n        }\n    }\n    return undefined;\n}\nexports.getFirstValueInFlattenedArray = getFirstValueInFlattenedArray;\nfunction getFirstKeyForCommand(commandName, args) {\n    if ((0, commands_1.exists)(commandName, { caseInsensitive: true })) {\n        const flattenedArgs = args.flat();\n        const keyIndexes = (0, commands_1.getKeyIndexes)(commandName, flattenedArgs, {\n            nameCaseInsensitive: true,\n        });\n        if (keyIndexes.length) {\n            return flattenedArgs[keyIndexes[0]];\n        }\n    }\n    return getFirstValueInFlattenedArray(args);\n}\nfunction executeWithAutoPipelining(client, functionName, commandName, args, callback) {\n    // On cluster mode let's wait for slots to be available\n    if (client.isCluster && !client.slots.length) {\n        if (client.status === \"wait\")\n            client.connect().catch(lodash_1.noop);\n        return (0, standard_as_callback_1.default)(new Promise(function (resolve, reject) {\n            client.delayUntilReady((err) => {\n                if (err) {\n                    reject(err);\n                    return;\n                }\n                executeWithAutoPipelining(client, functionName, commandName, args, null).then(resolve, reject);\n            });\n        }), callback);\n    }\n    // If we have slot information, we can improve routing by grouping slots served by the same subset of nodes\n    const prefix = client.options.keyPrefix || \"\";\n    let slotKey = client.isCluster\n        ? client.slots[calculateSlot(`${prefix}${getFirstKeyForCommand(commandName, args)}`)].join(\",\")\n        : \"main\";\n    // When scaleReads is enabled, separate read and write commands into different pipelines\n    // so they can be routed to replicas and masters respectively\n    if (client.isCluster && client.options.scaleReads !== \"master\") {\n        const isReadOnly = (0, commands_1.exists)(commandName) && (0, commands_1.hasFlag)(commandName, \"readonly\");\n        slotKey += isReadOnly ? \":read\" : \":write\";\n    }\n    if (!client._autoPipelines.has(slotKey)) {\n        const pipeline = client.pipeline();\n        pipeline[exports.kExec] = false;\n        pipeline[exports.kCallbacks] = [];\n        client._autoPipelines.set(slotKey, pipeline);\n    }\n    const pipeline = client._autoPipelines.get(slotKey);\n    /*\n      Mark the pipeline as scheduled.\n      The symbol will make sure that the pipeline is only scheduled once per tick.\n      New commands are appended to an already scheduled pipeline.\n    */\n    if (!pipeline[exports.kExec]) {\n        pipeline[exports.kExec] = true;\n        /*\n          Deferring with setImmediate so we have a chance to capture multiple\n          commands that can be scheduled by I/O events already in the event loop queue.\n        */\n        setImmediate(executeAutoPipeline, client, slotKey);\n    }\n    // Create the promise which will execute the command in the pipeline.\n    const autoPipelinePromise = new Promise(function (resolve, reject) {\n        pipeline[exports.kCallbacks].push(function (err, value) {\n            if (err) {\n                reject(err);\n                return;\n            }\n            resolve(value);\n        });\n        if (functionName === \"call\") {\n            args.unshift(commandName);\n        }\n        pipeline[functionName](...args);\n    });\n    return (0, standard_as_callback_1.default)(autoPipelinePromise, callback);\n}\nexports.executeWithAutoPipelining = executeWithAutoPipelining;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst crypto_1 = require(\"crypto\");\nconst Command_1 = require(\"./Command\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nclass Script {\n    constructor(lua, numberOfKeys = null, keyPrefix = \"\", readOnly = false) {\n        this.lua = lua;\n        this.numberOfKeys = numberOfKeys;\n        this.keyPrefix = keyPrefix;\n        this.readOnly = readOnly;\n        this.sha = (0, crypto_1.createHash)(\"sha1\").update(lua).digest(\"hex\");\n        const sha = this.sha;\n        const socketHasScriptLoaded = new WeakSet();\n        this.Command = class CustomScriptCommand extends Command_1.default {\n            toWritable(socket) {\n                const origReject = this.reject;\n                this.reject = (err) => {\n                    if (err.message.indexOf(\"NOSCRIPT\") !== -1) {\n                        socketHasScriptLoaded.delete(socket);\n                    }\n                    origReject.call(this, err);\n                };\n                if (!socketHasScriptLoaded.has(socket)) {\n                    socketHasScriptLoaded.add(socket);\n                    this.name = \"eval\";\n                    this.args[0] = lua;\n                }\n                else if (this.name === \"eval\") {\n                    this.name = \"evalsha\";\n                    this.args[0] = sha;\n                }\n                return super.toWritable(socket);\n            }\n        };\n    }\n    execute(container, args, options, callback) {\n        if (typeof this.numberOfKeys === \"number\") {\n            args.unshift(this.numberOfKeys);\n        }\n        if (this.keyPrefix) {\n            options.keyPrefix = this.keyPrefix;\n        }\n        if (this.readOnly) {\n            options.readOnly = true;\n        }\n        const evalsha = new this.Command(\"evalsha\", [this.sha, ...args], options);\n        evalsha.promise = evalsha.promise.catch((err) => {\n            if (err.message.indexOf(\"NOSCRIPT\") === -1) {\n                throw err;\n            }\n            // Resend the same custom evalsha command that gets transformed\n            // to an eval in case it's not loaded yet on the connection.\n            const resend = new this.Command(\"evalsha\", [this.sha, ...args], options);\n            const client = container.isPipeline ? container.redis : container;\n            return client.sendCommand(resend);\n        });\n        (0, standard_as_callback_1.default)(evalsha.promise, callback);\n        return container.sendCommand(evalsha);\n    }\n}\nexports.default = Script;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst autoPipelining_1 = require(\"../autoPipelining\");\nconst Command_1 = require(\"../Command\");\nconst Script_1 = require(\"../Script\");\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass Commander {\n    constructor() {\n        this.options = {};\n        /**\n         * @ignore\n         */\n        this.scriptsSet = {};\n        /**\n         * @ignore\n         */\n        this.addedBuiltinSet = new Set();\n    }\n    /**\n     * Return supported builtin commands\n     */\n    getBuiltinCommands() {\n        return commands.slice(0);\n    }\n    /**\n     * Create a builtin command\n     */\n    createBuiltinCommand(commandName) {\n        return {\n            string: generateFunction(null, commandName, \"utf8\"),\n            buffer: generateFunction(null, commandName, null),\n        };\n    }\n    /**\n     * Create add builtin command\n     */\n    addBuiltinCommand(commandName) {\n        this.addedBuiltinSet.add(commandName);\n        this[commandName] = generateFunction(commandName, commandName, \"utf8\");\n        this[commandName + \"Buffer\"] = generateFunction(commandName + \"Buffer\", commandName, null);\n    }\n    /**\n     * Define a custom command using lua script\n     */\n    defineCommand(name, definition) {\n        const script = new Script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly);\n        this.scriptsSet[name] = script;\n        this[name] = generateScriptingFunction(name, name, script, \"utf8\");\n        this[name + \"Buffer\"] = generateScriptingFunction(name + \"Buffer\", name, script, null);\n    }\n    /**\n     * @ignore\n     */\n    sendCommand(command, stream, node) {\n        throw new Error('\"sendCommand\" is not implemented');\n    }\n}\nconst commands = commands_1.list.filter((command) => command !== \"monitor\");\ncommands.push(\"sentinel\");\ncommands.forEach(function (commandName) {\n    Commander.prototype[commandName] = generateFunction(commandName, commandName, \"utf8\");\n    Commander.prototype[commandName + \"Buffer\"] = generateFunction(commandName + \"Buffer\", commandName, null);\n});\nCommander.prototype.call = generateFunction(\"call\", \"utf8\");\nCommander.prototype.callBuffer = generateFunction(\"callBuffer\", null);\n// @ts-expect-error\nCommander.prototype.send_command = Commander.prototype.call;\nfunction generateFunction(functionName, _commandName, _encoding) {\n    if (typeof _encoding === \"undefined\") {\n        _encoding = _commandName;\n        _commandName = null;\n    }\n    return function (...args) {\n        const commandName = (_commandName || args.shift());\n        let callback = args[args.length - 1];\n        if (typeof callback === \"function\") {\n            args.pop();\n        }\n        else {\n            callback = undefined;\n        }\n        const options = {\n            errorStack: this.options.showFriendlyErrorStack ? new Error() : undefined,\n            keyPrefix: this.options.keyPrefix,\n            replyEncoding: _encoding,\n        };\n        // No auto pipeline, use regular command sending\n        if (!(0, autoPipelining_1.shouldUseAutoPipelining)(this, functionName, commandName)) {\n            return this.sendCommand(\n            // @ts-expect-error\n            new Command_1.default(commandName, args, options, callback));\n        }\n        // Create a new pipeline and make sure it's scheduled\n        return (0, autoPipelining_1.executeWithAutoPipelining)(this, functionName, commandName, \n        // @ts-expect-error\n        args, callback);\n    };\n}\nfunction generateScriptingFunction(functionName, commandName, script, encoding) {\n    return function (...args) {\n        const callback = typeof args[args.length - 1] === \"function\" ? args.pop() : undefined;\n        const options = {\n            replyEncoding: encoding,\n        };\n        if (this.options.showFriendlyErrorStack) {\n            options.errorStack = new Error();\n        }\n        // No auto pipeline, use regular command sending\n        if (!(0, autoPipelining_1.shouldUseAutoPipelining)(this, functionName, commandName)) {\n            return script.execute(this, args, options, callback);\n        }\n        // Create a new pipeline and make sure it's scheduled\n        return (0, autoPipelining_1.executeWithAutoPipelining)(this, functionName, commandName, args, callback);\n    };\n}\nexports.default = Commander;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst calculateSlot = require(\"cluster-key-slot\");\nconst commands_1 = require(\"@ioredis/commands\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst util_1 = require(\"util\");\nconst Command_1 = require(\"./Command\");\nconst buffer_1 = require(\"buffer\");\nconst utils_1 = require(\"./utils\");\nconst Commander_1 = require(\"./utils/Commander\");\n/*\n  This function derives from the cluster-key-slot implementation.\n  Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes.\n  If this is satisfied, it returns the first key's slot.\n*/\nfunction generateMultiWithNodes(redis, keys) {\n    const slot = calculateSlot(keys[0]);\n    const target = redis._groupsBySlot[slot];\n    for (let i = 1; i < keys.length; i++) {\n        if (redis._groupsBySlot[calculateSlot(keys[i])] !== target) {\n            return -1;\n        }\n    }\n    return slot;\n}\nclass Pipeline extends Commander_1.default {\n    constructor(redis) {\n        super();\n        this.redis = redis;\n        this.isPipeline = true;\n        this.replyPending = 0;\n        this._queue = [];\n        this._result = [];\n        this._transactions = 0;\n        this._shaToScript = {};\n        this.isCluster =\n            this.redis.constructor.name === \"Cluster\" || this.redis.isCluster;\n        this.options = redis.options;\n        Object.keys(redis.scriptsSet).forEach((name) => {\n            const script = redis.scriptsSet[name];\n            this._shaToScript[script.sha] = script;\n            this[name] = redis[name];\n            this[name + \"Buffer\"] = redis[name + \"Buffer\"];\n        });\n        redis.addedBuiltinSet.forEach((name) => {\n            this[name] = redis[name];\n            this[name + \"Buffer\"] = redis[name + \"Buffer\"];\n        });\n        this.promise = new Promise((resolve, reject) => {\n            this.resolve = resolve;\n            this.reject = reject;\n        });\n        const _this = this;\n        Object.defineProperty(this, \"length\", {\n            get: function () {\n                return _this._queue.length;\n            },\n        });\n    }\n    fillResult(value, position) {\n        if (this._queue[position].name === \"exec\" && Array.isArray(value[1])) {\n            const execLength = value[1].length;\n            for (let i = 0; i < execLength; i++) {\n                if (value[1][i] instanceof Error) {\n                    continue;\n                }\n                const cmd = this._queue[position - (execLength - i)];\n                try {\n                    value[1][i] = cmd.transformReply(value[1][i]);\n                }\n                catch (err) {\n                    value[1][i] = err;\n                }\n            }\n        }\n        this._result[position] = value;\n        if (--this.replyPending) {\n            return;\n        }\n        if (this.isCluster) {\n            let retriable = true;\n            let commonError;\n            for (let i = 0; i < this._result.length; ++i) {\n                const error = this._result[i][0];\n                const command = this._queue[i];\n                if (error) {\n                    if (command.name === \"exec\" &&\n                        error.message ===\n                            \"EXECABORT Transaction discarded because of previous errors.\") {\n                        continue;\n                    }\n                    if (!commonError) {\n                        commonError = {\n                            name: error.name,\n                            message: error.message,\n                        };\n                    }\n                    else if (commonError.name !== error.name ||\n                        commonError.message !== error.message) {\n                        retriable = false;\n                        break;\n                    }\n                }\n                else if (!command.inTransaction) {\n                    const isReadOnly = (0, commands_1.exists)(command.name, { caseInsensitive: true }) &&\n                        (0, commands_1.hasFlag)(command.name, \"readonly\", { nameCaseInsensitive: true });\n                    if (!isReadOnly) {\n                        retriable = false;\n                        break;\n                    }\n                }\n            }\n            if (commonError && retriable) {\n                const _this = this;\n                const errv = commonError.message.split(\" \");\n                const queue = this._queue;\n                let inTransaction = false;\n                this._queue = [];\n                for (let i = 0; i < queue.length; ++i) {\n                    if (errv[0] === \"ASK\" &&\n                        !inTransaction &&\n                        queue[i].name !== \"asking\" &&\n                        (!queue[i - 1] || queue[i - 1].name !== \"asking\")) {\n                        const asking = new Command_1.default(\"asking\");\n                        asking.ignore = true;\n                        this.sendCommand(asking);\n                    }\n                    queue[i].initPromise();\n                    this.sendCommand(queue[i]);\n                    inTransaction = queue[i].inTransaction;\n                }\n                let matched = true;\n                if (typeof this.leftRedirections === \"undefined\") {\n                    this.leftRedirections = {};\n                }\n                const exec = function () {\n                    _this.exec();\n                };\n                const cluster = this.redis;\n                cluster.handleError(commonError, this.leftRedirections, {\n                    moved: function (_slot, key) {\n                        _this.preferKey = key;\n                        if (cluster.slots[errv[1]]) {\n                            if (cluster.slots[errv[1]][0] !== key) {\n                                cluster.slots[errv[1]] = [key];\n                            }\n                        }\n                        else {\n                            cluster.slots[errv[1]] = [key];\n                        }\n                        cluster._groupsBySlot[errv[1]] =\n                            cluster._groupsIds[cluster.slots[errv[1]].join(\";\")];\n                        cluster.refreshSlotsCache();\n                        _this.exec();\n                    },\n                    ask: function (_slot, key) {\n                        _this.preferKey = key;\n                        _this.exec();\n                    },\n                    tryagain: exec,\n                    clusterDown: exec,\n                    connectionClosed: exec,\n                    maxRedirections: () => {\n                        matched = false;\n                    },\n                    defaults: () => {\n                        matched = false;\n                    },\n                });\n                if (matched) {\n                    return;\n                }\n            }\n        }\n        let ignoredCount = 0;\n        for (let i = 0; i < this._queue.length - ignoredCount; ++i) {\n            if (this._queue[i + ignoredCount].ignore) {\n                ignoredCount += 1;\n            }\n            this._result[i] = this._result[i + ignoredCount];\n        }\n        this.resolve(this._result.slice(0, this._result.length - ignoredCount));\n    }\n    sendCommand(command) {\n        if (this._transactions > 0) {\n            command.inTransaction = true;\n        }\n        const position = this._queue.length;\n        command.pipelineIndex = position;\n        command.promise\n            .then((result) => {\n            this.fillResult([null, result], position);\n        })\n            .catch((error) => {\n            this.fillResult([error], position);\n        });\n        this._queue.push(command);\n        return this;\n    }\n    addBatch(commands) {\n        let command, commandName, args;\n        for (let i = 0; i < commands.length; ++i) {\n            command = commands[i];\n            commandName = command[0];\n            args = command.slice(1);\n            this[commandName].apply(this, args);\n        }\n        return this;\n    }\n}\nexports.default = Pipeline;\n// @ts-expect-error\nconst multi = Pipeline.prototype.multi;\n// @ts-expect-error\nPipeline.prototype.multi = function () {\n    this._transactions += 1;\n    return multi.apply(this, arguments);\n};\n// @ts-expect-error\nconst execBuffer = Pipeline.prototype.execBuffer;\n// @ts-expect-error\nPipeline.prototype.execBuffer = (0, util_1.deprecate)(function () {\n    if (this._transactions > 0) {\n        this._transactions -= 1;\n    }\n    return execBuffer.apply(this, arguments);\n}, \"Pipeline#execBuffer: Use Pipeline#exec instead\");\n// NOTE: To avoid an unhandled promise rejection, this will unconditionally always return this.promise,\n// which always has the rejection handled by standard-as-callback\n// adding the provided rejection callback.\n//\n// If a different promise instance were returned, that promise would cause its own unhandled promise rejection\n// errors, even if that promise unconditionally resolved to **the resolved value of** this.promise.\nPipeline.prototype.exec = function (callback) {\n    // Wait for the cluster to be connected, since we need nodes information before continuing\n    if (this.isCluster && !this.redis.slots.length) {\n        if (this.redis.status === \"wait\")\n            this.redis.connect().catch(utils_1.noop);\n        if (callback && !this.nodeifiedPromise) {\n            this.nodeifiedPromise = true;\n            (0, standard_as_callback_1.default)(this.promise, callback);\n        }\n        this.redis.delayUntilReady((err) => {\n            if (err) {\n                this.reject(err);\n                return;\n            }\n            this.exec(callback);\n        });\n        return this.promise;\n    }\n    if (this._transactions > 0) {\n        this._transactions -= 1;\n        return execBuffer.apply(this, arguments);\n    }\n    if (!this.nodeifiedPromise) {\n        this.nodeifiedPromise = true;\n        (0, standard_as_callback_1.default)(this.promise, callback);\n    }\n    if (!this._queue.length) {\n        this.resolve([]);\n    }\n    let pipelineSlot;\n    if (this.isCluster) {\n        // List of the first key for each command\n        const sampleKeys = [];\n        for (let i = 0; i < this._queue.length; i++) {\n            const keys = this._queue[i].getKeys();\n            if (keys.length) {\n                sampleKeys.push(keys[0]);\n            }\n            // For each command, check that the keys belong to the same slot\n            if (keys.length && calculateSlot.generateMulti(keys) < 0) {\n                this.reject(new Error(\"All the keys in a pipeline command should belong to the same slot\"));\n                return this.promise;\n            }\n        }\n        if (sampleKeys.length) {\n            pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys);\n            if (pipelineSlot < 0) {\n                this.reject(new Error(\"All keys in the pipeline should belong to the same slots allocation group\"));\n                return this.promise;\n            }\n        }\n        else {\n            // Send the pipeline to a random node\n            pipelineSlot = (Math.random() * 16384) | 0;\n        }\n    }\n    const _this = this;\n    execPipeline();\n    return this.promise;\n    function execPipeline() {\n        let writePending = (_this.replyPending = _this._queue.length);\n        let node;\n        if (_this.isCluster) {\n            node = {\n                slot: pipelineSlot,\n                redis: _this.redis.connectionPool.nodes.all[_this.preferKey],\n            };\n        }\n        let data = \"\";\n        let buffers;\n        const stream = {\n            isPipeline: true,\n            destination: _this.isCluster ? node : { redis: _this.redis },\n            write(writable) {\n                if (typeof writable !== \"string\") {\n                    if (!buffers) {\n                        buffers = [];\n                    }\n                    if (data) {\n                        buffers.push(Buffer.from(data, \"utf8\"));\n                        data = \"\";\n                    }\n                    buffers.push(writable);\n                }\n                else {\n                    if (data.length + writable.length >= buffer_1.constants.MAX_STRING_LENGTH) {\n                        if (!buffers) {\n                            buffers = [];\n                        }\n                        if (data) {\n                            buffers.push(Buffer.from(data, \"utf8\"));\n                            data = \"\";\n                        }\n                    }\n                    data += writable;\n                }\n                if (!--writePending) {\n                    if (buffers) {\n                        if (data) {\n                            buffers.push(Buffer.from(data, \"utf8\"));\n                        }\n                        stream.destination.redis.stream.write(Buffer.concat(buffers));\n                    }\n                    else {\n                        stream.destination.redis.stream.write(data);\n                    }\n                    // Reset writePending for resending\n                    writePending = _this._queue.length;\n                    data = \"\";\n                    buffers = undefined;\n                }\n            },\n        };\n        for (let i = 0; i < _this._queue.length; ++i) {\n            _this.redis.sendCommand(_this._queue[i], stream, node);\n        }\n        return _this.promise;\n    }\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.traceConnect = exports.traceBatch = exports.traceCommand = exports.sanitizeArgs = void 0;\n// Argument sanitization rules adapted from @opentelemetry/redis-common (Apache 2.0).\n// https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/packages/redis-common/src/index.ts\n//\n// Each entry specifies how many positional args (after the command name) are safe\n// to emit. -1 means all args are safe (read-only/structural commands).\n// Unlisted commands default to 0 (all args redacted) for safe-by-default behavior,\n// which covers AUTH, HELLO, and unknown/custom commands.\nconst SERIALIZATION_SUBSETS = [\n    { regex: /^ECHO/i, args: 0 },\n    {\n        regex: /^(LPUSH|MSET|PFA|PUBLISH|RPUSH|SADD|SET|SPUBLISH|XADD|ZADD)/i,\n        args: 1,\n    },\n    { regex: /^(HSET|HMSET|LSET|LINSERT)/i, args: 2 },\n    {\n        regex: /^(ACL|BIT|B[LRZ]|CLIENT|CLUSTER|CONFIG|COMMAND|DECR|DEL|EVAL|EX|FUNCTION|GEO|GET|HINCR|HMGET|HSCAN|INCR|L[TRLM]|MEMORY|P[EFISTU]|RPOP|S[CDIMORSU]|XACK|X[CDGILPRT]|Z[CDILMPRS])/i,\n        args: -1,\n    },\n];\nfunction sanitizeArgs(commandName, args) {\n    let allowedArgCount = 0;\n    for (const subset of SERIALIZATION_SUBSETS) {\n        if (subset.regex.test(commandName)) {\n            allowedArgCount = subset.args;\n            break;\n        }\n    }\n    if (allowedArgCount === -1) {\n        return args.map((a) => String(a));\n    }\n    const result = [];\n    for (let i = 0; i < args.length; i++) {\n        if (i < allowedArgCount) {\n            result.push(String(args[i]));\n        }\n        else {\n            result.push(\"?\");\n        }\n    }\n    return result;\n}\nexports.sanitizeArgs = sanitizeArgs;\n// Load diagnostics_channel with Node 18 compatibility\nconst dc = (() => {\n    try {\n        return \"getBuiltinModule\" in process\n            ? process.getBuiltinModule(\"node:diagnostics_channel\")\n            : require(\"node:diagnostics_channel\");\n    }\n    catch {\n        return undefined;\n    }\n})();\nconst hasTracingChannel = dc && typeof dc.tracingChannel === \"function\";\nconst commandChannel = hasTracingChannel\n    ? dc.tracingChannel(\"ioredis:command\")\n    : undefined;\nconst batchChannel = hasTracingChannel\n    ? dc.tracingChannel(\"ioredis:batch\")\n    : undefined;\nconst connectChannel = hasTracingChannel\n    ? dc.tracingChannel(\"ioredis:connect\")\n    : undefined;\nfunction shouldTrace(channel) {\n    return !!channel && channel.hasSubscribers !== false;\n}\nconst noop = () => { };\nfunction traceCommand(fn, contextFactory) {\n    if (!shouldTrace(commandChannel))\n        return fn();\n    // tracePromise returns a wrapper promise that re-rejects on error.\n    // Silence the wrapper to prevent unhandled rejections when callers\n    // (e.g. Pipeline) discard the return value. Callers that await this\n    // promise still see the rejection through their own .then() chain.\n    const traced = commandChannel.tracePromise(fn, contextFactory());\n    traced.catch(noop);\n    return traced;\n}\nexports.traceCommand = traceCommand;\nfunction traceBatch(fn, contextFactory) {\n    if (!shouldTrace(batchChannel))\n        return fn();\n    const traced = batchChannel.tracePromise(fn, contextFactory());\n    traced.catch(noop);\n    return traced;\n}\nexports.traceBatch = traceBatch;\nfunction traceConnect(fn, contextFactory) {\n    if (!shouldTrace(connectChannel))\n        return fn();\n    return connectChannel.tracePromise(fn, contextFactory());\n}\nexports.traceConnect = traceConnect;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.addTransactionSupport = void 0;\nconst utils_1 = require(\"./utils\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst Pipeline_1 = require(\"./Pipeline\");\nconst tracing_1 = require(\"./tracing\");\nfunction addTransactionSupport(redis) {\n    redis.pipeline = function (commands) {\n        const pipeline = new Pipeline_1.default(this);\n        if (Array.isArray(commands)) {\n            pipeline.addBatch(commands);\n        }\n        return pipeline;\n    };\n    const { multi } = redis;\n    redis.multi = function (commands, options) {\n        if (typeof options === \"undefined\" && !Array.isArray(commands)) {\n            options = commands;\n            commands = null;\n        }\n        if (options && options.pipeline === false) {\n            return multi.call(this);\n        }\n        const pipeline = new Pipeline_1.default(this);\n        // @ts-expect-error\n        pipeline.multi();\n        if (Array.isArray(commands)) {\n            pipeline.addBatch(commands);\n        }\n        const exec = pipeline.exec;\n        pipeline.exec = function (callback) {\n            // Wait for the cluster to be connected, since we need nodes information before continuing\n            if (this.isCluster && !this.redis.slots.length) {\n                if (this.redis.status === \"wait\")\n                    this.redis.connect().catch(utils_1.noop);\n                return (0, standard_as_callback_1.default)(new Promise((resolve, reject) => {\n                    this.redis.delayUntilReady((err) => {\n                        if (err) {\n                            reject(err);\n                            return;\n                        }\n                        this.exec(pipeline).then(resolve, reject);\n                    });\n                }), callback);\n            }\n            if (this._transactions > 0) {\n                exec.call(pipeline);\n            }\n            // Returns directly when the pipeline\n            // has been called multiple times (retries).\n            if (this.nodeifiedPromise) {\n                return exec.call(pipeline);\n            }\n            // Count only user commands (exclude MULTI/EXEC wrappers).\n            const batchSize = Math.max(pipeline.length - 2, 0);\n            const execAndUnwrap = () => exec.call(pipeline).then(function (result) {\n                const execResult = result[result.length - 1];\n                if (typeof execResult === \"undefined\") {\n                    throw new Error(\"Pipeline cannot be used to send any commands when the `exec()` has been called on it.\");\n                }\n                if (execResult[0]) {\n                    execResult[0].previousErrors = [];\n                    for (let i = 0; i < result.length - 1; ++i) {\n                        if (result[i][0]) {\n                            execResult[0].previousErrors.push(result[i][0]);\n                        }\n                    }\n                    throw execResult[0];\n                }\n                return (0, utils_1.wrapMultiResult)(execResult[1]);\n            });\n            // Trace MULTI as a single batch operation on ioredis:batch.\n            const promise = \"_buildBatchContext\" in this.redis\n                ? (0, tracing_1.traceBatch)(execAndUnwrap, () => this.redis._buildBatchContext(batchSize))\n                : execAndUnwrap();\n            return (0, standard_as_callback_1.default)(promise, callback);\n        };\n        // @ts-expect-error\n        const { execBuffer } = pipeline;\n        // @ts-expect-error\n        pipeline.execBuffer = function (callback) {\n            if (this._transactions > 0) {\n                execBuffer.call(pipeline);\n            }\n            return pipeline.exec(callback);\n        };\n        return pipeline;\n    };\n    const { exec } = redis;\n    redis.exec = function (callback) {\n        return (0, standard_as_callback_1.default)(exec.call(this).then(function (results) {\n            if (Array.isArray(results)) {\n                results = (0, utils_1.wrapMultiResult)(results);\n            }\n            return results;\n        }), callback);\n    };\n}\nexports.addTransactionSupport = addTransactionSupport;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction applyMixin(derivedConstructor, mixinConstructor) {\n    Object.getOwnPropertyNames(mixinConstructor.prototype).forEach((name) => {\n        Object.defineProperty(derivedConstructor.prototype, name, Object.getOwnPropertyDescriptor(mixinConstructor.prototype, name));\n    });\n}\nexports.default = applyMixin;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_CLUSTER_OPTIONS = void 0;\nconst dns_1 = require(\"dns\");\nexports.DEFAULT_CLUSTER_OPTIONS = {\n    clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000),\n    clusterNodeRetryStrategy: null,\n    enableOfflineQueue: true,\n    enableReadyCheck: true,\n    scaleReads: \"master\",\n    maxRedirections: 16,\n    retryDelayOnMoved: 0,\n    retryDelayOnFailover: 100,\n    retryDelayOnClusterDown: 100,\n    retryDelayOnTryAgain: 100,\n    slotsRefreshTimeout: 1000,\n    useSRVRecords: false,\n    resolveSrv: dns_1.resolveSrv,\n    dnsLookup: dns_1.lookup,\n    enableAutoPipelining: false,\n    autoPipeliningIgnoredCommands: [],\n    shardedSubscribers: false,\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getConnectionName = exports.weightSrvRecords = exports.groupSrvRecords = exports.getUniqueHostnamesFromOptions = exports.normalizeNodeOptions = exports.nodeKeyToRedisOptions = exports.getNodeKey = void 0;\nconst utils_1 = require(\"../utils\");\nconst net_1 = require(\"net\");\nfunction getNodeKey(node) {\n    node.port = node.port || 6379;\n    node.host = node.host || \"127.0.0.1\";\n    return node.host + \":\" + node.port;\n}\nexports.getNodeKey = getNodeKey;\nfunction nodeKeyToRedisOptions(nodeKey) {\n    const portIndex = nodeKey.lastIndexOf(\":\");\n    if (portIndex === -1) {\n        throw new Error(`Invalid node key ${nodeKey}`);\n    }\n    return {\n        host: nodeKey.slice(0, portIndex),\n        port: Number(nodeKey.slice(portIndex + 1)),\n    };\n}\nexports.nodeKeyToRedisOptions = nodeKeyToRedisOptions;\nfunction normalizeNodeOptions(nodes) {\n    return nodes.map((node) => {\n        const options = {};\n        if (typeof node === \"object\") {\n            Object.assign(options, node);\n        }\n        else if (typeof node === \"string\") {\n            Object.assign(options, (0, utils_1.parseURL)(node));\n        }\n        else if (typeof node === \"number\") {\n            options.port = node;\n        }\n        else {\n            throw new Error(\"Invalid argument \" + node);\n        }\n        if (typeof options.port === \"string\") {\n            options.port = parseInt(options.port, 10);\n        }\n        // Cluster mode only support db 0\n        delete options.db;\n        if (!options.port) {\n            options.port = 6379;\n        }\n        if (!options.host) {\n            options.host = \"127.0.0.1\";\n        }\n        return (0, utils_1.resolveTLSProfile)(options);\n    });\n}\nexports.normalizeNodeOptions = normalizeNodeOptions;\nfunction getUniqueHostnamesFromOptions(nodes) {\n    const uniqueHostsMap = {};\n    nodes.forEach((node) => {\n        uniqueHostsMap[node.host] = true;\n    });\n    return Object.keys(uniqueHostsMap).filter((host) => !(0, net_1.isIP)(host));\n}\nexports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions;\nfunction groupSrvRecords(records) {\n    const recordsByPriority = {};\n    for (const record of records) {\n        if (!recordsByPriority.hasOwnProperty(record.priority)) {\n            recordsByPriority[record.priority] = {\n                totalWeight: record.weight,\n                records: [record],\n            };\n        }\n        else {\n            recordsByPriority[record.priority].totalWeight += record.weight;\n            recordsByPriority[record.priority].records.push(record);\n        }\n    }\n    return recordsByPriority;\n}\nexports.groupSrvRecords = groupSrvRecords;\nfunction weightSrvRecords(recordsGroup) {\n    if (recordsGroup.records.length === 1) {\n        recordsGroup.totalWeight = 0;\n        return recordsGroup.records.shift();\n    }\n    // + `recordsGroup.records.length` to support `weight` 0\n    const random = Math.floor(Math.random() * (recordsGroup.totalWeight + recordsGroup.records.length));\n    let total = 0;\n    for (const [i, record] of recordsGroup.records.entries()) {\n        total += 1 + record.weight;\n        if (total > random) {\n            recordsGroup.totalWeight -= record.weight;\n            recordsGroup.records.splice(i, 1);\n            return record;\n        }\n    }\n}\nexports.weightSrvRecords = weightSrvRecords;\nfunction getConnectionName(component, nodeConnectionName) {\n    const prefix = `ioredis-cluster(${component})`;\n    return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix;\n}\nexports.getConnectionName = getConnectionName;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"./util\");\nconst utils_1 = require(\"../utils\");\nconst Redis_1 = require(\"../Redis\");\nconst debug = (0, utils_1.Debug)(\"cluster:subscriber\");\nclass ClusterSubscriber {\n    constructor(connectionPool, emitter, isSharded = false) {\n        this.connectionPool = connectionPool;\n        this.emitter = emitter;\n        this.isSharded = isSharded;\n        this.started = false;\n        //There is only one connection for the entire pool\n        this.subscriber = null;\n        //The slot range for which this subscriber is responsible\n        this.slotRange = [];\n        this.onSubscriberEnd = () => {\n            if (!this.started) {\n                debug(\"subscriber has disconnected, but ClusterSubscriber is not started, so not reconnecting.\");\n                return;\n            }\n            // If the subscriber closes whilst it's still the active connection,\n            // we might as well try to connecting to a new node if possible to\n            // minimise the number of missed publishes.\n            debug(\"subscriber has disconnected, selecting a new one...\");\n            this.selectSubscriber();\n        };\n        // If the current node we're using as the subscriber disappears\n        // from the node pool for some reason, we will select a new one\n        // to connect to.\n        // Note that this event is only triggered if the connection to\n        // the node has been used; cluster subscriptions are setup with\n        // lazyConnect = true. It's possible for the subscriber node to\n        // disappear without this method being called!\n        // See https://github.com/luin/ioredis/pull/1589\n        this.connectionPool.on(\"-node\", (_, key) => {\n            if (!this.started || !this.subscriber) {\n                return;\n            }\n            if ((0, util_1.getNodeKey)(this.subscriber.options) === key) {\n                debug(\"subscriber has left, selecting a new one...\");\n                this.selectSubscriber();\n            }\n        });\n        this.connectionPool.on(\"+node\", () => {\n            if (!this.started || this.subscriber) {\n                return;\n            }\n            debug(\"a new node is discovered and there is no subscriber, selecting a new one...\");\n            this.selectSubscriber();\n        });\n    }\n    getInstance() {\n        return this.subscriber;\n    }\n    /**\n     * Associate this subscriber to a specific slot range.\n     *\n     * Returns the range or an empty array if the slot range couldn't be associated.\n     *\n     * BTW: This is more for debugging and testing purposes.\n     *\n     * @param range\n     */\n    associateSlotRange(range) {\n        if (this.isSharded) {\n            this.slotRange = range;\n        }\n        return this.slotRange;\n    }\n    start() {\n        this.started = true;\n        this.selectSubscriber();\n        debug(\"started\");\n    }\n    stop() {\n        this.started = false;\n        if (this.subscriber) {\n            this.subscriber.disconnect();\n            this.subscriber = null;\n        }\n    }\n    isStarted() {\n        return this.started;\n    }\n    selectSubscriber() {\n        const lastActiveSubscriber = this.lastActiveSubscriber;\n        // Disconnect the previous subscriber even if there\n        // will not be a new one.\n        if (lastActiveSubscriber) {\n            lastActiveSubscriber.off(\"end\", this.onSubscriberEnd);\n            lastActiveSubscriber.disconnect();\n        }\n        if (this.subscriber) {\n            this.subscriber.off(\"end\", this.onSubscriberEnd);\n            this.subscriber.disconnect();\n        }\n        const sampleNode = (0, utils_1.sample)(this.connectionPool.getNodes());\n        if (!sampleNode) {\n            debug(\"selecting subscriber failed since there is no node discovered in the cluster yet\");\n            this.subscriber = null;\n            return;\n        }\n        const { options } = sampleNode;\n        debug(\"selected a subscriber %s:%s\", options.host, options.port);\n        /*\n         * Create a specialized Redis connection for the subscription.\n         * Note that auto reconnection is enabled here.\n         *\n         * `enableReadyCheck` is also enabled because although subscription is allowed\n         * while redis is loading data from the disk, we can check if the password\n         * provided for the subscriber is correct, and if not, the current subscriber\n         * will be disconnected and a new subscriber will be selected.\n         */\n        let connectionPrefix = \"subscriber\";\n        if (this.isSharded)\n            connectionPrefix = \"ssubscriber\";\n        this.subscriber = new Redis_1.default({\n            port: options.port,\n            host: options.host,\n            username: options.username,\n            password: options.password,\n            enableReadyCheck: true,\n            connectionName: (0, util_1.getConnectionName)(connectionPrefix, options.connectionName),\n            lazyConnect: true,\n            tls: options.tls,\n            // Don't try to reconnect the subscriber connection. If the connection fails\n            // we will get an end event (handled below), at which point we'll pick a new\n            // node from the pool and try to connect to that as the subscriber connection.\n            retryStrategy: null,\n        });\n        // Ignore the errors since they're handled in the connection pool.\n        this.subscriber.on(\"error\", utils_1.noop);\n        this.subscriber.on(\"moved\", () => {\n            this.emitter.emit(\"forceRefresh\");\n        });\n        // The node we lost connection to may not come back up in a\n        // reasonable amount of time (e.g. a slave that's taken down\n        // for maintainence), we could potentially miss many published\n        // messages so we should reconnect as quickly as possible, to\n        // a different node if needed.\n        this.subscriber.once(\"end\", this.onSubscriberEnd);\n        // Re-subscribe previous channels\n        const previousChannels = { subscribe: [], psubscribe: [], ssubscribe: [] };\n        if (lastActiveSubscriber) {\n            const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition;\n            if (condition && condition.subscriber) {\n                previousChannels.subscribe = condition.subscriber.channels(\"subscribe\");\n                previousChannels.psubscribe =\n                    condition.subscriber.channels(\"psubscribe\");\n                previousChannels.ssubscribe =\n                    condition.subscriber.channels(\"ssubscribe\");\n            }\n        }\n        if (previousChannels.subscribe.length ||\n            previousChannels.psubscribe.length ||\n            previousChannels.ssubscribe.length) {\n            let pending = 0;\n            for (const type of [\"subscribe\", \"psubscribe\", \"ssubscribe\"]) {\n                const channels = previousChannels[type];\n                if (channels.length == 0) {\n                    continue;\n                }\n                debug(\"%s %d channels\", type, channels.length);\n                if (type === \"ssubscribe\") {\n                    for (const channel of channels) {\n                        pending += 1;\n                        this.subscriber[type](channel)\n                            .then(() => {\n                            if (!--pending) {\n                                this.lastActiveSubscriber = this.subscriber;\n                            }\n                        })\n                            .catch(() => {\n                            // TODO: should probably disconnect the subscriber and try again.\n                            debug(\"failed to ssubscribe to channel: %s\", channel);\n                        });\n                    }\n                }\n                else {\n                    pending += 1;\n                    this.subscriber[type](channels)\n                        .then(() => {\n                        if (!--pending) {\n                            this.lastActiveSubscriber = this.subscriber;\n                        }\n                    })\n                        .catch(() => {\n                        // TODO: should probably disconnect the subscriber and try again.\n                        debug(\"failed to %s %d channels\", type, channels.length);\n                    });\n                }\n            }\n        }\n        else {\n            this.lastActiveSubscriber = this.subscriber;\n        }\n        for (const event of [\n            \"message\",\n            \"messageBuffer\",\n        ]) {\n            this.subscriber.on(event, (arg1, arg2) => {\n                this.emitter.emit(event, arg1, arg2);\n            });\n        }\n        for (const event of [\"pmessage\", \"pmessageBuffer\"]) {\n            this.subscriber.on(event, (arg1, arg2, arg3) => {\n                this.emitter.emit(event, arg1, arg2, arg3);\n            });\n        }\n        if (this.isSharded == true) {\n            for (const event of [\n                \"smessage\",\n                \"smessageBuffer\",\n            ]) {\n                this.subscriber.on(event, (arg1, arg2) => {\n                    this.emitter.emit(event, arg1, arg2);\n                });\n            }\n        }\n    }\n}\nexports.default = ClusterSubscriber;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst events_1 = require(\"events\");\nconst utils_1 = require(\"../utils\");\nconst util_1 = require(\"./util\");\nconst Redis_1 = require(\"../Redis\");\nconst debug = (0, utils_1.Debug)(\"cluster:connectionPool\");\nclass ConnectionPool extends events_1.EventEmitter {\n    constructor(redisOptions, clusterNodeRetryStrategy = null) {\n        super();\n        this.redisOptions = redisOptions;\n        this.clusterNodeRetryStrategy = clusterNodeRetryStrategy;\n        // master + slave = all\n        this.nodes = {\n            all: {},\n            master: {},\n            slave: {},\n        };\n        this.specifiedOptions = {};\n    }\n    getNodes(role = \"all\") {\n        const nodes = this.nodes[role];\n        return Object.keys(nodes).map((key) => nodes[key]);\n    }\n    getInstanceByKey(key) {\n        return this.nodes.all[key];\n    }\n    getSampleInstance(role) {\n        const keys = Object.keys(this.nodes[role]);\n        const sampleKey = (0, utils_1.sample)(keys);\n        return this.nodes[role][sampleKey];\n    }\n    /**\n     * Add a master node to the pool\n     * @param node\n     */\n    addMasterNode(node) {\n        const key = (0, util_1.getNodeKey)(node.options);\n        const redis = this.createRedisFromOptions(node, node.options.readOnly);\n        //Master nodes aren't read-only\n        if (!node.options.readOnly) {\n            this.nodes.all[key] = redis;\n            this.nodes.master[key] = redis;\n            return true;\n        }\n        return false;\n    }\n    /**\n     * Creates a Redis connection instance from the node options\n     * @param node\n     * @param readOnly\n     */\n    createRedisFromOptions(node, readOnly) {\n        const redis = new Redis_1.default((0, utils_1.defaults)({\n            // By default, never try to reconnect when a node is lost,\n            // instead, waiting for a `MOVED` error and fetching slots again.\n            // When `clusterNodeRetryStrategy` is set, use it to allow\n            // reconnection (e.g. for replica nodes that restart without\n            // any slot changes).\n            retryStrategy: typeof this.clusterNodeRetryStrategy === \"function\"\n                ? this.clusterNodeRetryStrategy\n                : null,\n            // Offline queue should be enabled so that\n            // we don't need to wait for the `ready` event\n            // before sending commands to the node.\n            enableOfflineQueue: true,\n            readOnly: readOnly,\n        }, node, this.redisOptions, { lazyConnect: true }));\n        return redis;\n    }\n    /**\n     * Find or create a connection to the node\n     */\n    findOrCreate(node, readOnly = false) {\n        const key = (0, util_1.getNodeKey)(node);\n        readOnly = Boolean(readOnly);\n        if (this.specifiedOptions[key]) {\n            Object.assign(node, this.specifiedOptions[key]);\n        }\n        else {\n            this.specifiedOptions[key] = node;\n        }\n        let redis;\n        if (this.nodes.all[key]) {\n            redis = this.nodes.all[key];\n            if (redis.options.readOnly !== readOnly) {\n                redis.options.readOnly = readOnly;\n                debug(\"Change role of %s to %s\", key, readOnly ? \"slave\" : \"master\");\n                redis[readOnly ? \"readonly\" : \"readwrite\"]().catch(utils_1.noop);\n                if (readOnly) {\n                    delete this.nodes.master[key];\n                    this.nodes.slave[key] = redis;\n                }\n                else {\n                    delete this.nodes.slave[key];\n                    this.nodes.master[key] = redis;\n                }\n            }\n        }\n        else {\n            debug(\"Connecting to %s as %s\", key, readOnly ? \"slave\" : \"master\");\n            redis = this.createRedisFromOptions(node, readOnly);\n            this.nodes.all[key] = redis;\n            this.nodes[readOnly ? \"slave\" : \"master\"][key] = redis;\n            redis.once(\"end\", () => {\n                this.removeNode(key);\n                this.emit(\"-node\", redis, key);\n                if (!Object.keys(this.nodes.all).length) {\n                    this.emit(\"drain\");\n                }\n            });\n            this.emit(\"+node\", redis, key);\n            redis.on(\"error\", (error) => {\n                this.emit(\"nodeError\", error, key);\n            });\n        }\n        return redis;\n    }\n    /**\n     * Reset the pool with a set of nodes.\n     * The old node will be removed.\n     */\n    reset(nodes) {\n        debug(\"Reset with %O\", nodes);\n        const newNodes = {};\n        nodes.forEach((node) => {\n            const key = (0, util_1.getNodeKey)(node);\n            // Don't override the existing (master) node\n            // when the current one is slave.\n            if (!(node.readOnly && newNodes[key])) {\n                newNodes[key] = node;\n            }\n        });\n        Object.keys(this.nodes.all).forEach((key) => {\n            if (!newNodes[key]) {\n                debug(\"Disconnect %s because the node does not hold any slot\", key);\n                this.nodes.all[key].disconnect();\n                this.removeNode(key);\n            }\n        });\n        Object.keys(newNodes).forEach((key) => {\n            const node = newNodes[key];\n            this.findOrCreate(node, node.readOnly);\n        });\n    }\n    /**\n     * Remove a node from the pool.\n     */\n    removeNode(key) {\n        const { nodes } = this;\n        if (nodes.all[key]) {\n            debug(\"Remove %s from the pool\", key);\n            delete nodes.all[key];\n        }\n        delete nodes.master[key];\n        delete nodes.slave[key];\n    }\n}\nexports.default = ConnectionPool;\n","'use strict';\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction Denque(array, options) {\n  var options = options || {};\n  this._capacity = options.capacity;\n\n  this._head = 0;\n  this._tail = 0;\n\n  if (Array.isArray(array)) {\n    this._fromArray(array);\n  } else {\n    this._capacityMask = 0x3;\n    this._list = new Array(4);\n  }\n}\n\n/**\n * --------------\n *  PUBLIC API\n * -------------\n */\n\n/**\n * Returns the item at the specified index from the list.\n * 0 is the first element, 1 is the second, and so on...\n * Elements at negative values are that many from the end: -1 is one before the end\n * (the last element), -2 is two before the end (one before last), etc.\n * @param index\n * @returns {*}\n */\nDenque.prototype.peekAt = function peekAt(index) {\n  var i = index;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  var len = this.size();\n  if (i >= len || i < -len) return undefined;\n  if (i < 0) i += len;\n  i = (this._head + i) & this._capacityMask;\n  return this._list[i];\n};\n\n/**\n * Alias for peekAt()\n * @param i\n * @returns {*}\n */\nDenque.prototype.get = function get(i) {\n  return this.peekAt(i);\n};\n\n/**\n * Returns the first item in the list without removing it.\n * @returns {*}\n */\nDenque.prototype.peek = function peek() {\n  if (this._head === this._tail) return undefined;\n  return this._list[this._head];\n};\n\n/**\n * Alias for peek()\n * @returns {*}\n */\nDenque.prototype.peekFront = function peekFront() {\n  return this.peek();\n};\n\n/**\n * Returns the item that is at the back of the queue without removing it.\n * Uses peekAt(-1)\n */\nDenque.prototype.peekBack = function peekBack() {\n  return this.peekAt(-1);\n};\n\n/**\n * Returns the current length of the queue\n * @return {Number}\n */\nObject.defineProperty(Denque.prototype, 'length', {\n  get: function length() {\n    return this.size();\n  }\n});\n\n/**\n * Return the number of items on the list, or 0 if empty.\n * @returns {number}\n */\nDenque.prototype.size = function size() {\n  if (this._head === this._tail) return 0;\n  if (this._head < this._tail) return this._tail - this._head;\n  else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Add an item at the beginning of the list.\n * @param item\n */\nDenque.prototype.unshift = function unshift(item) {\n  if (arguments.length === 0) return this.size();\n  var len = this._list.length;\n  this._head = (this._head - 1 + len) & this._capacityMask;\n  this._list[this._head] = item;\n  if (this._tail === this._head) this._growArray();\n  if (this._capacity && this.size() > this._capacity) this.pop();\n  if (this._head < this._tail) return this._tail - this._head;\n  else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the first item on the list,\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.shift = function shift() {\n  var head = this._head;\n  if (head === this._tail) return undefined;\n  var item = this._list[head];\n  this._list[head] = undefined;\n  this._head = (head + 1) & this._capacityMask;\n  if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();\n  return item;\n};\n\n/**\n * Add an item to the bottom of the list.\n * @param item\n */\nDenque.prototype.push = function push(item) {\n  if (arguments.length === 0) return this.size();\n  var tail = this._tail;\n  this._list[tail] = item;\n  this._tail = (tail + 1) & this._capacityMask;\n  if (this._tail === this._head) {\n    this._growArray();\n  }\n  if (this._capacity && this.size() > this._capacity) {\n    this.shift();\n  }\n  if (this._head < this._tail) return this._tail - this._head;\n  else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the last item on the list.\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.pop = function pop() {\n  var tail = this._tail;\n  if (tail === this._head) return undefined;\n  var len = this._list.length;\n  this._tail = (tail - 1 + len) & this._capacityMask;\n  var item = this._list[this._tail];\n  this._list[this._tail] = undefined;\n  if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();\n  return item;\n};\n\n/**\n * Remove and return the item at the specified index from the list.\n * Returns undefined if the list is empty.\n * @param index\n * @returns {*}\n */\nDenque.prototype.removeOne = function removeOne(index) {\n  var i = index;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  if (this._head === this._tail) return void 0;\n  var size = this.size();\n  var len = this._list.length;\n  if (i >= size || i < -size) return void 0;\n  if (i < 0) i += size;\n  i = (this._head + i) & this._capacityMask;\n  var item = this._list[i];\n  var k;\n  if (index < size / 2) {\n    for (k = index; k > 0; k--) {\n      this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];\n    }\n    this._list[i] = void 0;\n    this._head = (this._head + 1 + len) & this._capacityMask;\n  } else {\n    for (k = size - 1 - index; k > 0; k--) {\n      this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask];\n    }\n    this._list[i] = void 0;\n    this._tail = (this._tail - 1 + len) & this._capacityMask;\n  }\n  return item;\n};\n\n/**\n * Remove number of items from the specified index from the list.\n * Returns array of removed items.\n * Returns undefined if the list is empty.\n * @param index\n * @param count\n * @returns {array}\n */\nDenque.prototype.remove = function remove(index, count) {\n  var i = index;\n  var removed;\n  var del_count = count;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  if (this._head === this._tail) return void 0;\n  var size = this.size();\n  var len = this._list.length;\n  if (i >= size || i < -size || count < 1) return void 0;\n  if (i < 0) i += size;\n  if (count === 1 || !count) {\n    removed = new Array(1);\n    removed[0] = this.removeOne(i);\n    return removed;\n  }\n  if (i === 0 && i + count >= size) {\n    removed = this.toArray();\n    this.clear();\n    return removed;\n  }\n  if (i + count > size) count = size - i;\n  var k;\n  removed = new Array(count);\n  for (k = 0; k < count; k++) {\n    removed[k] = this._list[(this._head + i + k) & this._capacityMask];\n  }\n  i = (this._head + i) & this._capacityMask;\n  if (index + count === size) {\n    this._tail = (this._tail - count + len) & this._capacityMask;\n    for (k = count; k > 0; k--) {\n      this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n    }\n    return removed;\n  }\n  if (index === 0) {\n    this._head = (this._head + count + len) & this._capacityMask;\n    for (k = count - 1; k > 0; k--) {\n      this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n    }\n    return removed;\n  }\n  if (i < size / 2) {\n    this._head = (this._head + index + count + len) & this._capacityMask;\n    for (k = index; k > 0; k--) {\n      this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);\n    }\n    i = (this._head - 1 + len) & this._capacityMask;\n    while (del_count > 0) {\n      this._list[i = (i - 1 + len) & this._capacityMask] = void 0;\n      del_count--;\n    }\n    if (index < 0) this._tail = i;\n  } else {\n    this._tail = i;\n    i = (i + count + len) & this._capacityMask;\n    for (k = size - (count + index); k > 0; k--) {\n      this.push(this._list[i++]);\n    }\n    i = this._tail;\n    while (del_count > 0) {\n      this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n      del_count--;\n    }\n  }\n  if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();\n  return removed;\n};\n\n/**\n * Native splice implementation.\n * Remove number of items from the specified index from the list and/or add new elements.\n * Returns array of removed items or empty array if count == 0.\n * Returns undefined if the list is empty.\n *\n * @param index\n * @param count\n * @param {...*} [elements]\n * @returns {array}\n */\nDenque.prototype.splice = function splice(index, count) {\n  var i = index;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  var size = this.size();\n  if (i < 0) i += size;\n  if (i > size) return void 0;\n  if (arguments.length > 2) {\n    var k;\n    var temp;\n    var removed;\n    var arg_len = arguments.length;\n    var len = this._list.length;\n    var arguments_index = 2;\n    if (!size || i < size / 2) {\n      temp = new Array(i);\n      for (k = 0; k < i; k++) {\n        temp[k] = this._list[(this._head + k) & this._capacityMask];\n      }\n      if (count === 0) {\n        removed = [];\n        if (i > 0) {\n          this._head = (this._head + i + len) & this._capacityMask;\n        }\n      } else {\n        removed = this.remove(i, count);\n        this._head = (this._head + i + len) & this._capacityMask;\n      }\n      while (arg_len > arguments_index) {\n        this.unshift(arguments[--arg_len]);\n      }\n      for (k = i; k > 0; k--) {\n        this.unshift(temp[k - 1]);\n      }\n    } else {\n      temp = new Array(size - (i + count));\n      var leng = temp.length;\n      for (k = 0; k < leng; k++) {\n        temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];\n      }\n      if (count === 0) {\n        removed = [];\n        if (i != size) {\n          this._tail = (this._head + i + len) & this._capacityMask;\n        }\n      } else {\n        removed = this.remove(i, count);\n        this._tail = (this._tail - leng + len) & this._capacityMask;\n      }\n      while (arguments_index < arg_len) {\n        this.push(arguments[arguments_index++]);\n      }\n      for (k = 0; k < leng; k++) {\n        this.push(temp[k]);\n      }\n    }\n    return removed;\n  } else {\n    return this.remove(i, count);\n  }\n};\n\n/**\n * Soft clear - does not reset capacity.\n */\nDenque.prototype.clear = function clear() {\n  this._list = new Array(this._list.length);\n  this._head = 0;\n  this._tail = 0;\n};\n\n/**\n * Returns true or false whether the list is empty.\n * @returns {boolean}\n */\nDenque.prototype.isEmpty = function isEmpty() {\n  return this._head === this._tail;\n};\n\n/**\n * Returns an array of all queue items.\n * @returns {Array}\n */\nDenque.prototype.toArray = function toArray() {\n  return this._copyArray(false);\n};\n\n/**\n * -------------\n *   INTERNALS\n * -------------\n */\n\n/**\n * Fills the queue with items from an array\n * For use in the constructor\n * @param array\n * @private\n */\nDenque.prototype._fromArray = function _fromArray(array) {\n  var length = array.length;\n  var capacity = this._nextPowerOf2(length);\n\n  this._list = new Array(capacity);\n  this._capacityMask = capacity - 1;\n  this._tail = length;\n\n  for (var i = 0; i < length; i++) this._list[i] = array[i];\n};\n\n/**\n *\n * @param fullCopy\n * @param size Initialize the array with a specific size. Will default to the current list size\n * @returns {Array}\n * @private\n */\nDenque.prototype._copyArray = function _copyArray(fullCopy, size) {\n  var src = this._list;\n  var capacity = src.length;\n  var length = this.length;\n  size = size | length;\n\n  // No prealloc requested and the buffer is contiguous\n  if (size == length && this._head < this._tail) {\n    // Simply do a fast slice copy\n    return this._list.slice(this._head, this._tail);\n  }\n\n  var dest = new Array(size);\n\n  var k = 0;\n  var i;\n  if (fullCopy || this._head > this._tail) {\n    for (i = this._head; i < capacity; i++) dest[k++] = src[i];\n    for (i = 0; i < this._tail; i++) dest[k++] = src[i];\n  } else {\n    for (i = this._head; i < this._tail; i++) dest[k++] = src[i];\n  }\n\n  return dest;\n}\n\n/**\n * Grows the internal list array.\n * @private\n */\nDenque.prototype._growArray = function _growArray() {\n  if (this._head != 0) {\n    // double array size and copy existing data, head to end, then beginning to tail.\n    var newList = this._copyArray(true, this._list.length << 1);\n\n    this._tail = this._list.length;\n    this._head = 0;\n\n    this._list = newList;\n  } else {\n    this._tail = this._list.length;\n    this._list.length <<= 1;\n  }\n\n  this._capacityMask = (this._capacityMask << 1) | 1;\n};\n\n/**\n * Shrinks the internal list array.\n * @private\n */\nDenque.prototype._shrinkArray = function _shrinkArray() {\n  this._list.length >>>= 1;\n  this._capacityMask >>>= 1;\n};\n\n/**\n * Find the next power of 2, at least 4\n * @private\n * @param {number} num \n * @returns {number}\n */\nDenque.prototype._nextPowerOf2 = function _nextPowerOf2(num) {\n  var log2 = Math.log(num) / Math.log(2);\n  var nextPow2 = 1 << (log2 + 1);\n\n  return Math.max(nextPow2, 4);\n}\n\nmodule.exports = Denque;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"../utils\");\nconst Deque = require(\"denque\");\nconst debug = (0, utils_1.Debug)(\"delayqueue\");\n/**\n * Queue that runs items after specified duration\n */\nclass DelayQueue {\n    constructor() {\n        this.queues = {};\n        this.timeouts = {};\n    }\n    /**\n     * Add a new item to the queue\n     *\n     * @param bucket bucket name\n     * @param item function that will run later\n     * @param options\n     */\n    push(bucket, item, options) {\n        const callback = options.callback || process.nextTick;\n        if (!this.queues[bucket]) {\n            this.queues[bucket] = new Deque();\n        }\n        const queue = this.queues[bucket];\n        queue.push(item);\n        if (!this.timeouts[bucket]) {\n            this.timeouts[bucket] = setTimeout(() => {\n                callback(() => {\n                    this.timeouts[bucket] = null;\n                    this.execute(bucket);\n                });\n            }, options.timeout);\n        }\n    }\n    execute(bucket) {\n        const queue = this.queues[bucket];\n        if (!queue) {\n            return;\n        }\n        const { length } = queue;\n        if (!length) {\n            return;\n        }\n        debug(\"send %d commands in %s queue\", length, bucket);\n        this.queues[bucket] = null;\n        while (queue.length > 0) {\n            queue.shift()();\n        }\n    }\n}\nexports.default = DelayQueue;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"./util\");\nconst utils_1 = require(\"../utils\");\nconst Redis_1 = require(\"../Redis\");\nconst debug = (0, utils_1.Debug)(\"cluster:subscriberGroup:shardedSubscriber\");\nconst SubscriberStatus = {\n    IDLE: \"idle\",\n    STARTING: \"starting\",\n    CONNECTED: \"connected\",\n    STOPPING: \"stopping\",\n    ENDED: \"ended\",\n};\nconst ALLOWED_STATUS_UPDATES = {\n    [SubscriberStatus.IDLE]: [\n        SubscriberStatus.STARTING,\n        SubscriberStatus.STOPPING,\n        SubscriberStatus.ENDED,\n    ],\n    [SubscriberStatus.STARTING]: [\n        SubscriberStatus.CONNECTED,\n        SubscriberStatus.STOPPING,\n        SubscriberStatus.ENDED,\n    ],\n    [SubscriberStatus.CONNECTED]: [\n        SubscriberStatus.STOPPING,\n        SubscriberStatus.ENDED,\n    ],\n    [SubscriberStatus.STOPPING]: [SubscriberStatus.ENDED],\n    [SubscriberStatus.ENDED]: [],\n};\nclass ShardedSubscriber {\n    constructor(emitter, options, redisOptions) {\n        var _a;\n        this.emitter = emitter;\n        this.status = SubscriberStatus.IDLE;\n        this.instance = null;\n        this.connectPromise = null;\n        // Store listener references for cleanup\n        this.messageListeners = new Map();\n        this.onEnd = () => {\n            this.updateStatus(SubscriberStatus.ENDED);\n            this.emitter.emit(\"-node\", this.instance, this.nodeKey);\n        };\n        this.onError = (error) => {\n            this.emitter.emit(\"nodeError\", error, this.nodeKey);\n        };\n        this.onMoved = () => {\n            this.emitter.emit(\"moved\");\n        };\n        this.instance = new Redis_1.default((0, utils_1.defaults)({\n            enableReadyCheck: false,\n            enableOfflineQueue: true,\n            connectionName: (0, util_1.getConnectionName)(\"ssubscriber\", options.connectionName),\n            /**\n             * Disable auto reconnection for subscribers.\n             * The ClusterSubscriberGroup will handle the reconnection.\n             */\n            retryStrategy: null,\n            lazyConnect: true,\n        }, options, redisOptions));\n        this.lazyConnect = (_a = redisOptions === null || redisOptions === void 0 ? void 0 : redisOptions.lazyConnect) !== null && _a !== void 0 ? _a : true;\n        this.nodeKey = (0, util_1.getNodeKey)(options);\n        // Register listeners\n        this.instance.on(\"end\", this.onEnd);\n        this.instance.on(\"error\", this.onError);\n        this.instance.on(\"moved\", this.onMoved);\n        for (const event of [\"smessage\", \"smessageBuffer\"]) {\n            const listener = (...args) => {\n                this.emitter.emit(event, ...args);\n            };\n            this.messageListeners.set(event, listener);\n            this.instance.on(event, listener);\n        }\n    }\n    async start() {\n        if (this.connectPromise) {\n            return this.connectPromise;\n        }\n        if (this.status === SubscriberStatus.STARTING ||\n            this.status === SubscriberStatus.CONNECTED) {\n            return;\n        }\n        if (this.status === SubscriberStatus.ENDED || !this.instance) {\n            throw new Error(`Sharded subscriber ${this.nodeKey} cannot be restarted once ended.`);\n        }\n        this.updateStatus(SubscriberStatus.STARTING);\n        this.connectPromise = this.instance.connect();\n        try {\n            await this.connectPromise;\n            this.updateStatus(SubscriberStatus.CONNECTED);\n        }\n        catch (err) {\n            this.updateStatus(SubscriberStatus.ENDED);\n            throw err;\n        }\n        finally {\n            this.connectPromise = null;\n        }\n    }\n    stop() {\n        this.updateStatus(SubscriberStatus.STOPPING);\n        if (this.instance) {\n            this.instance.disconnect();\n            this.instance.removeAllListeners();\n            this.messageListeners.clear();\n            this.instance = null;\n        }\n        this.updateStatus(SubscriberStatus.ENDED);\n        debug(\"stopped %s\", this.nodeKey);\n    }\n    isStarted() {\n        return [\n            SubscriberStatus.CONNECTED,\n            SubscriberStatus.STARTING,\n        ].includes(this.status);\n    }\n    get subscriberStatus() {\n        return this.status;\n    }\n    isHealthy() {\n        return ((this.status === SubscriberStatus.IDLE ||\n            this.status === SubscriberStatus.CONNECTED ||\n            this.status === SubscriberStatus.STARTING) &&\n            this.instance !== null);\n    }\n    getInstance() {\n        return this.instance;\n    }\n    getNodeKey() {\n        return this.nodeKey;\n    }\n    isLazyConnect() {\n        return this.lazyConnect;\n    }\n    updateStatus(nextStatus) {\n        if (this.status === nextStatus) {\n            return;\n        }\n        if (!ALLOWED_STATUS_UPDATES[this.status].includes(nextStatus)) {\n            debug(\"Invalid status transition for %s: %s -> %s\", this.nodeKey, this.status, nextStatus);\n            return;\n        }\n        this.status = nextStatus;\n    }\n}\nexports.default = ShardedSubscriber;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"../utils\");\nconst util_1 = require(\"./util\");\nconst calculateSlot = require(\"cluster-key-slot\");\nconst ShardedSubscriber_1 = require(\"./ShardedSubscriber\");\nconst debug = (0, utils_1.Debug)(\"cluster:subscriberGroup\");\n/**\n * Redis distinguishes between \"normal\" and sharded PubSub. When using the normal PubSub feature,\n * exactly one subscriber exists per cluster instance because the Redis cluster bus forwards\n * messages between shards. Sharded PubSub removes this limitation by making each shard\n * responsible for its own messages.\n *\n * This class coordinates one ShardedSubscriber per master node in the cluster, providing\n * sharded PubSub support while keeping the public API backward compatible.\n */\nclass ClusterSubscriberGroup {\n    /**\n     * Register callbacks\n     *\n     * @param cluster\n     */\n    constructor(subscriberGroupEmitter, options) {\n        this.subscriberGroupEmitter = subscriberGroupEmitter;\n        this.options = options;\n        this.shardedSubscribers = new Map();\n        this.clusterSlots = [];\n        // Simple [min, max] slot ranges aren't enough because you can migrate single slots\n        this.subscriberToSlotsIndex = new Map();\n        this.channels = new Map();\n        this.failedAttemptsByNode = new Map();\n        // Only latest pending reset kept; throttled by refreshSlotsCache's isRefreshing + backoff delay\n        this.isResetting = false;\n        this.pendingReset = null;\n        /**\n         * Handles failed subscriber connections by emitting an event to refresh the slots cache\n         * after a backoff period.\n         *\n         * @param error\n         * @param nodeKey\n         */\n        this.handleSubscriberConnectFailed = (error, nodeKey) => {\n            const currentAttempts = this.failedAttemptsByNode.get(nodeKey) || 0;\n            const failedAttempts = currentAttempts + 1;\n            this.failedAttemptsByNode.set(nodeKey, failedAttempts);\n            const attempts = Math.min(failedAttempts, ClusterSubscriberGroup.MAX_RETRY_ATTEMPTS);\n            const backoff = Math.min(ClusterSubscriberGroup.BASE_BACKOFF_MS * 2 ** attempts, ClusterSubscriberGroup.MAX_BACKOFF_MS);\n            const jitter = Math.floor((Math.random() - 0.5) * (backoff * 0.5));\n            const delay = Math.max(0, backoff + jitter);\n            debug(\"Failed to connect subscriber for %s. Refreshing slots in %dms\", nodeKey, delay);\n            this.subscriberGroupEmitter.emit(\"subscriberConnectFailed\", {\n                delay,\n                error,\n            });\n        };\n        /**\n         * Handles successful subscriber connections by resetting the failed attempts counter.\n         *\n         * @param nodeKey\n         */\n        this.handleSubscriberConnectSucceeded = (nodeKey) => {\n            this.failedAttemptsByNode.delete(nodeKey);\n        };\n    }\n    /**\n     * Get the responsible subscriber.\n     *\n     * @param slot\n     */\n    getResponsibleSubscriber(slot) {\n        const nodeKey = this.clusterSlots[slot][0];\n        const sub = this.shardedSubscribers.get(nodeKey);\n        if (sub && sub.subscriberStatus === \"idle\") {\n            sub\n                .start()\n                .then(() => {\n                this.handleSubscriberConnectSucceeded(sub.getNodeKey());\n            })\n                .catch((err) => {\n                this.handleSubscriberConnectFailed(err, sub.getNodeKey());\n            });\n        }\n        return sub;\n    }\n    /**\n     * Adds a channel for which this subscriber group is responsible\n     *\n     * @param channels\n     */\n    addChannels(channels) {\n        const slot = calculateSlot(channels[0]);\n        // Check if the all channels belong to the same slot and otherwise reject the operation\n        for (const c of channels) {\n            if (calculateSlot(c) !== slot) {\n                return -1;\n            }\n        }\n        const currChannels = this.channels.get(slot);\n        if (!currChannels) {\n            this.channels.set(slot, channels);\n        }\n        else {\n            this.channels.set(slot, currChannels.concat(channels));\n        }\n        return Array.from(this.channels.values()).reduce((sum, array) => sum + array.length, 0);\n    }\n    /**\n     * Removes channels for which the subscriber group is responsible by optionally unsubscribing\n     * @param channels\n     */\n    removeChannels(channels) {\n        const slot = calculateSlot(channels[0]);\n        // Check if the all channels belong to the same slot and otherwise reject the operation\n        for (const c of channels) {\n            if (calculateSlot(c) !== slot) {\n                return -1;\n            }\n        }\n        const slotChannels = this.channels.get(slot);\n        if (slotChannels) {\n            const updatedChannels = slotChannels.filter((c) => !channels.includes(c));\n            this.channels.set(slot, updatedChannels);\n        }\n        return Array.from(this.channels.values()).reduce((sum, array) => sum + array.length, 0);\n    }\n    /**\n     * Disconnect all subscribers and clear some of the internal state.\n     */\n    stop() {\n        for (const s of this.shardedSubscribers.values()) {\n            s.stop();\n        }\n        // Clear subscriber instances and pending operations.\n        // Channels are preserved for resubscription on reconnect.\n        this.pendingReset = null;\n        this.shardedSubscribers.clear();\n        this.subscriberToSlotsIndex.clear();\n    }\n    /**\n     * Start all not yet started subscribers\n     */\n    start() {\n        const startPromises = [];\n        for (const s of this.shardedSubscribers.values()) {\n            if (this.shouldStartSubscriber(s)) {\n                startPromises.push(s\n                    .start()\n                    .then(() => {\n                    this.handleSubscriberConnectSucceeded(s.getNodeKey());\n                })\n                    .catch((err) => {\n                    this.handleSubscriberConnectFailed(err, s.getNodeKey());\n                }));\n                this.subscriberGroupEmitter.emit(\"+subscriber\");\n            }\n        }\n        return Promise.all(startPromises);\n    }\n    /**\n     * Resets the subscriber group by disconnecting all subscribers that are no longer needed and connecting new ones.\n     */\n    async reset(clusterSlots, clusterNodes) {\n        if (this.isResetting) {\n            this.pendingReset = { slots: clusterSlots, nodes: clusterNodes };\n            return;\n        }\n        this.isResetting = true;\n        try {\n            const hasTopologyChanged = this._refreshSlots(clusterSlots);\n            const hasFailedSubscribers = this.hasUnhealthySubscribers();\n            if (!hasTopologyChanged && !hasFailedSubscribers) {\n                debug(\"No topology change detected or failed subscribers. Skipping reset.\");\n                return;\n            }\n            // For each of the sharded subscribers\n            for (const [nodeKey, shardedSubscriber] of this.shardedSubscribers) {\n                if (\n                // If the subscriber is still responsible for a slot range and is healthy then keep it\n                this.subscriberToSlotsIndex.has(nodeKey) &&\n                    shardedSubscriber.isHealthy()) {\n                    debug(\"Skipping deleting subscriber for %s\", nodeKey);\n                    continue;\n                }\n                debug(\"Removing subscriber for %s\", nodeKey);\n                // Otherwise stop the subscriber and remove it\n                shardedSubscriber.stop();\n                this.shardedSubscribers.delete(nodeKey);\n                this.subscriberGroupEmitter.emit(\"-subscriber\");\n            }\n            const startPromises = [];\n            // For each node in slots cache\n            for (const [nodeKey, _] of this.subscriberToSlotsIndex) {\n                const existingSubscriber = this.shardedSubscribers.get(nodeKey);\n                // If we already have a subscriber for this node, only ensure it is healthy\n                // when it now owns slots with active channel subscriptions.\n                if (existingSubscriber && existingSubscriber.isHealthy()) {\n                    debug(\"Skipping creating new subscriber for %s\", nodeKey);\n                    if (!existingSubscriber.isStarted() &&\n                        this.shouldStartSubscriber(existingSubscriber)) {\n                        startPromises.push(existingSubscriber\n                            .start()\n                            .then(() => {\n                            this.handleSubscriberConnectSucceeded(nodeKey);\n                        })\n                            .catch((error) => {\n                            this.handleSubscriberConnectFailed(error, nodeKey);\n                        }));\n                    }\n                    continue;\n                }\n                // If we have an existing subscriber but it is not healthy, stop it\n                if (existingSubscriber && !existingSubscriber.isHealthy()) {\n                    debug(\"Replacing subscriber for %s\", nodeKey);\n                    existingSubscriber.stop();\n                    this.shardedSubscribers.delete(nodeKey);\n                    this.subscriberGroupEmitter.emit(\"-subscriber\");\n                }\n                debug(\"Creating new subscriber for %s\", nodeKey);\n                // Otherwise create a new subscriber\n                const redis = clusterNodes.find((node) => {\n                    return (0, util_1.getNodeKey)(node.options) === nodeKey;\n                });\n                if (!redis) {\n                    debug(\"Failed to find node for key %s\", nodeKey);\n                    continue;\n                }\n                const sub = new ShardedSubscriber_1.default(this.subscriberGroupEmitter, redis.options, this.options.redisOptions);\n                this.shardedSubscribers.set(nodeKey, sub);\n                if (this.shouldStartSubscriber(sub)) {\n                    startPromises.push(sub\n                        .start()\n                        .then(() => {\n                        this.handleSubscriberConnectSucceeded(nodeKey);\n                    })\n                        .catch((error) => {\n                        this.handleSubscriberConnectFailed(error, nodeKey);\n                    }));\n                }\n                this.subscriberGroupEmitter.emit(\"+subscriber\");\n            }\n            // It's vital to await the start promises before resubscribing\n            // Otherwise we might try to resubscribe to a subscriber that is not yet connected\n            // This can cause a race condition\n            await Promise.all(startPromises);\n            this._resubscribe();\n            this.subscriberGroupEmitter.emit(\"subscribersReady\");\n        }\n        finally {\n            this.isResetting = false;\n            if (this.pendingReset) {\n                const { slots, nodes } = this.pendingReset;\n                this.pendingReset = null;\n                await this.reset(slots, nodes);\n            }\n        }\n    }\n    /**\n     * Refreshes the subscriber-related slot ranges\n     *\n     * Returns false if no refresh was needed\n     *\n     * @param targetSlots\n     */\n    _refreshSlots(targetSlots) {\n        //If there was an actual change, then reassign the slot ranges\n        // Also rebuild if subscriberToSlotsIndex is empty (e.g., after stop() was called)\n        if (this._slotsAreEqual(targetSlots) && this.subscriberToSlotsIndex.size > 0) {\n            debug(\"Nothing to refresh because the new cluster map is equal to the previous one.\");\n            return false;\n        }\n        debug(\"Refreshing the slots of the subscriber group.\");\n        //Rebuild the slots index\n        this.subscriberToSlotsIndex = new Map();\n        for (let slot = 0; slot < targetSlots.length; slot++) {\n            const node = targetSlots[slot][0];\n            if (!this.subscriberToSlotsIndex.has(node)) {\n                this.subscriberToSlotsIndex.set(node, []);\n            }\n            this.subscriberToSlotsIndex.get(node).push(Number(slot));\n        }\n        //Update the cached slots map\n        this.clusterSlots = JSON.parse(JSON.stringify(targetSlots));\n        return true;\n    }\n    /**\n     * Resubscribes to the previous channels\n     *\n     * @private\n     */\n    _resubscribe() {\n        if (this.shardedSubscribers) {\n            this.shardedSubscribers.forEach((s, nodeKey) => {\n                const subscriberSlots = this.subscriberToSlotsIndex.get(nodeKey);\n                if (subscriberSlots) {\n                    //Resubscribe on the underlying connection\n                    subscriberSlots.forEach((ss) => {\n                        //Might return null if being disconnected\n                        const redis = s.getInstance();\n                        const channels = this.channels.get(ss);\n                        if (channels && channels.length > 0) {\n                            if (!redis || redis.status === \"end\") {\n                                return;\n                            }\n                            if (redis.status === \"ready\") {\n                                redis.ssubscribe(...channels).catch((err) => {\n                                    // TODO: Should we emit an error event here?\n                                    debug(\"Failed to ssubscribe on node %s: %s\", nodeKey, err);\n                                });\n                            }\n                            else {\n                                redis.once(\"ready\", () => {\n                                    redis.ssubscribe(...channels).catch((err) => {\n                                        // TODO: Should we emit an error event here?\n                                        debug(\"Failed to ssubscribe on node %s: %s\", nodeKey, err);\n                                    });\n                                });\n                            }\n                        }\n                    });\n                }\n            });\n        }\n    }\n    /**\n     * Deep equality of the cluster slots objects\n     *\n     * @param other\n     * @private\n     */\n    _slotsAreEqual(other) {\n        if (this.clusterSlots === undefined) {\n            return false;\n        }\n        else {\n            return JSON.stringify(this.clusterSlots) === JSON.stringify(other);\n        }\n    }\n    /**\n     * Checks if any subscribers are in an unhealthy state.\n     *\n     * A subscriber is considered unhealthy if:\n     * - It exists but is not started (failed/disconnected)\n     * - It's missing entirely for a node that should have one\n     *\n     * @returns true if any subscribers need to be recreated\n     */\n    hasUnhealthySubscribers() {\n        const hasFailedSubscribers = Array.from(this.shardedSubscribers.values()).some((sub) => !sub.isHealthy());\n        const hasMissingSubscribers = Array.from(this.subscriberToSlotsIndex.keys()).some((nodeKey) => !this.shardedSubscribers.has(nodeKey));\n        return hasFailedSubscribers || hasMissingSubscribers;\n    }\n    shouldStartSubscriber(sub) {\n        if (sub.isStarted()) {\n            return false;\n        }\n        if (!sub.isLazyConnect()) {\n            return true;\n        }\n        const subscriberSlots = this.subscriberToSlotsIndex.get(sub.getNodeKey());\n        if (!subscriberSlots) {\n            return false;\n        }\n        return subscriberSlots.some((slot) => {\n            const channels = this.channels.get(slot);\n            return Boolean(channels && channels.length > 0);\n        });\n    }\n}\nexports.default = ClusterSubscriberGroup;\n// Retry strategy\nClusterSubscriberGroup.MAX_RETRY_ATTEMPTS = 10;\nClusterSubscriberGroup.MAX_BACKOFF_MS = 2000;\nClusterSubscriberGroup.BASE_BACKOFF_MS = 100;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst events_1 = require(\"events\");\nconst redis_errors_1 = require(\"redis-errors\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst Command_1 = require(\"../Command\");\nconst ClusterAllFailedError_1 = require(\"../errors/ClusterAllFailedError\");\nconst Redis_1 = require(\"../Redis\");\nconst ScanStream_1 = require(\"../ScanStream\");\nconst transaction_1 = require(\"../transaction\");\nconst utils_1 = require(\"../utils\");\nconst applyMixin_1 = require(\"../utils/applyMixin\");\nconst Commander_1 = require(\"../utils/Commander\");\nconst ClusterOptions_1 = require(\"./ClusterOptions\");\nconst ClusterSubscriber_1 = require(\"./ClusterSubscriber\");\nconst ConnectionPool_1 = require(\"./ConnectionPool\");\nconst DelayQueue_1 = require(\"./DelayQueue\");\nconst util_1 = require(\"./util\");\nconst Deque = require(\"denque\");\nconst ClusterSubscriberGroup_1 = require(\"./ClusterSubscriberGroup\");\nconst debug = (0, utils_1.Debug)(\"cluster\");\nconst REJECT_OVERWRITTEN_COMMANDS = new WeakSet();\n/**\n * Client for the official Redis Cluster\n */\nclass Cluster extends Commander_1.default {\n    /**\n     * Creates an instance of Cluster.\n     */\n    //TODO: Add an option that enables or disables sharded PubSub\n    constructor(startupNodes, options = {}) {\n        var _a;\n        super();\n        this.slots = [];\n        /**\n         * @ignore\n         */\n        this._groupsIds = {};\n        /**\n         * @ignore\n         */\n        this._groupsBySlot = Array(16384);\n        /**\n         * @ignore\n         */\n        this.isCluster = true;\n        this.retryAttempts = 0;\n        this.delayQueue = new DelayQueue_1.default();\n        this.offlineQueue = new Deque();\n        this.isRefreshing = false;\n        this._refreshSlotsCacheCallbacks = [];\n        this._autoPipelines = new Map();\n        this._runningAutoPipelines = new Set();\n        this._readyDelayedCallbacks = [];\n        /**\n         * Every time Cluster#connect() is called, this value will be\n         * auto-incrementing. The purpose of this value is used for\n         * discarding previous connect attampts when creating a new\n         * connection.\n         */\n        this.connectionEpoch = 0;\n        events_1.EventEmitter.call(this);\n        this.startupNodes = startupNodes;\n        this.options = (0, utils_1.defaults)({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options);\n        if (this.options.shardedSubscribers) {\n            this.createShardedSubscriberGroup();\n        }\n        if (this.options.redisOptions &&\n            this.options.redisOptions.keyPrefix &&\n            !this.options.keyPrefix) {\n            this.options.keyPrefix = this.options.redisOptions.keyPrefix;\n        }\n        // validate options\n        if (typeof this.options.scaleReads !== \"function\" &&\n            [\"all\", \"master\", \"slave\"].indexOf(this.options.scaleReads) === -1) {\n            throw new Error('Invalid option scaleReads \"' +\n                this.options.scaleReads +\n                '\". Expected \"all\", \"master\", \"slave\" or a custom function');\n        }\n        this.connectionPool = new ConnectionPool_1.default((_a = this.options.redisOptions) !== null && _a !== void 0 ? _a : {}, this.options.clusterNodeRetryStrategy);\n        this.connectionPool.on(\"-node\", (redis, key) => {\n            this.emit(\"-node\", redis);\n        });\n        this.connectionPool.on(\"+node\", (redis) => {\n            this.emit(\"+node\", redis);\n        });\n        this.connectionPool.on(\"drain\", () => {\n            this.setStatus(\"close\");\n        });\n        this.connectionPool.on(\"nodeError\", (error, key) => {\n            this.emit(\"node error\", error, key);\n        });\n        this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this);\n        if (this.options.scripts) {\n            Object.entries(this.options.scripts).forEach(([name, definition]) => {\n                this.defineCommand(name, definition);\n            });\n        }\n        if (this.options.lazyConnect) {\n            this.setStatus(\"wait\");\n        }\n        else {\n            this.connect().catch((err) => {\n                debug(\"connecting failed: %s\", err);\n            });\n        }\n    }\n    /**\n     * Connect to a cluster\n     */\n    connect() {\n        return new Promise((resolve, reject) => {\n            if (this.status === \"connecting\" ||\n                this.status === \"connect\" ||\n                this.status === \"ready\") {\n                reject(new Error(\"Redis is already connecting/connected\"));\n                return;\n            }\n            const epoch = ++this.connectionEpoch;\n            this.setStatus(\"connecting\");\n            this.resolveStartupNodeHostnames()\n                .then((nodes) => {\n                if (this.connectionEpoch !== epoch) {\n                    debug(\"discard connecting after resolving startup nodes because epoch not match: %d != %d\", epoch, this.connectionEpoch);\n                    reject(new redis_errors_1.RedisError(\"Connection is discarded because a new connection is made\"));\n                    return;\n                }\n                if (this.status !== \"connecting\") {\n                    debug(\"discard connecting after resolving startup nodes because the status changed to %s\", this.status);\n                    reject(new redis_errors_1.RedisError(\"Connection is aborted\"));\n                    return;\n                }\n                this.connectionPool.reset(nodes);\n                if (this.options.shardedSubscribers) {\n                    this.shardedSubscribers\n                        .reset(this.slots, this.connectionPool.getNodes(\"all\"))\n                        .catch((err) => {\n                        // TODO should we emit an error event here?\n                        debug(\"Error while starting subscribers: %s\", err);\n                    });\n                }\n                const readyHandler = () => {\n                    this.setStatus(\"ready\");\n                    this.retryAttempts = 0;\n                    this.executeOfflineCommands();\n                    this.resetNodesRefreshInterval();\n                    resolve();\n                };\n                let closeListener = undefined;\n                const refreshListener = () => {\n                    this.invokeReadyDelayedCallbacks(undefined);\n                    this.removeListener(\"close\", closeListener);\n                    this.manuallyClosing = false;\n                    this.setStatus(\"connect\");\n                    if (this.options.enableReadyCheck) {\n                        this.readyCheck((err, fail) => {\n                            if (err || fail) {\n                                debug(\"Ready check failed (%s). Reconnecting...\", err || fail);\n                                if (this.status === \"connect\") {\n                                    this.disconnect(true);\n                                }\n                            }\n                            else {\n                                readyHandler();\n                            }\n                        });\n                    }\n                    else {\n                        readyHandler();\n                    }\n                };\n                closeListener = () => {\n                    const error = new Error(\"None of startup nodes is available\");\n                    this.removeListener(\"refresh\", refreshListener);\n                    this.invokeReadyDelayedCallbacks(error);\n                    reject(error);\n                };\n                this.once(\"refresh\", refreshListener);\n                this.once(\"close\", closeListener);\n                this.once(\"close\", this.handleCloseEvent.bind(this));\n                this.refreshSlotsCache((err) => {\n                    if (err && err.message === ClusterAllFailedError_1.default.defaultMessage) {\n                        Redis_1.default.prototype.silentEmit.call(this, \"error\", err);\n                        this.connectionPool.reset([]);\n                    }\n                });\n                this.subscriber.start();\n                if (this.options.shardedSubscribers) {\n                    this.shardedSubscribers.start().catch((err) => {\n                        // TODO should we emit an error event here?\n                        debug(\"Error while starting subscribers: %s\", err);\n                    });\n                }\n            })\n                .catch((err) => {\n                this.setStatus(\"close\");\n                this.handleCloseEvent(err);\n                this.invokeReadyDelayedCallbacks(err);\n                reject(err);\n            });\n        });\n    }\n    /**\n     * Disconnect from every node in the cluster.\n     */\n    disconnect(reconnect = false) {\n        const status = this.status;\n        this.setStatus(\"disconnecting\");\n        if (!reconnect) {\n            this.manuallyClosing = true;\n        }\n        if (this.reconnectTimeout && !reconnect) {\n            clearTimeout(this.reconnectTimeout);\n            this.reconnectTimeout = null;\n            debug(\"Canceled reconnecting attempts\");\n        }\n        this.clearNodesRefreshInterval();\n        this.subscriber.stop();\n        if (this.options.shardedSubscribers) {\n            this.shardedSubscribers.stop();\n        }\n        if (status === \"wait\") {\n            this.setStatus(\"close\");\n            this.handleCloseEvent();\n        }\n        else {\n            this.connectionPool.reset([]);\n        }\n    }\n    /**\n     * Quit the cluster gracefully.\n     */\n    quit(callback) {\n        const status = this.status;\n        this.setStatus(\"disconnecting\");\n        this.manuallyClosing = true;\n        if (this.reconnectTimeout) {\n            clearTimeout(this.reconnectTimeout);\n            this.reconnectTimeout = null;\n        }\n        this.clearNodesRefreshInterval();\n        this.subscriber.stop();\n        if (this.options.shardedSubscribers) {\n            this.shardedSubscribers.stop();\n        }\n        if (status === \"wait\") {\n            const ret = (0, standard_as_callback_1.default)(Promise.resolve(\"OK\"), callback);\n            // use setImmediate to make sure \"close\" event\n            // being emitted after quit() is returned\n            setImmediate(function () {\n                this.setStatus(\"close\");\n                this.handleCloseEvent();\n            }.bind(this));\n            return ret;\n        }\n        return (0, standard_as_callback_1.default)(Promise.all(this.nodes().map((node) => node.quit().catch((err) => {\n            // Ignore the error caused by disconnecting since\n            // we're disconnecting...\n            if (err.message === utils_1.CONNECTION_CLOSED_ERROR_MSG) {\n                return \"OK\";\n            }\n            throw err;\n        }))).then(() => \"OK\"), callback);\n    }\n    /**\n     * Create a new instance with the same startup nodes and options as the current one.\n     *\n     * @example\n     * ```js\n     * var cluster = new Redis.Cluster([{ host: \"127.0.0.1\", port: \"30001\" }]);\n     * var anotherCluster = cluster.duplicate();\n     * ```\n     */\n    duplicate(overrideStartupNodes = [], overrideOptions = {}) {\n        const startupNodes = overrideStartupNodes.length > 0\n            ? overrideStartupNodes\n            : this.startupNodes.slice(0);\n        const options = Object.assign({}, this.options, overrideOptions);\n        return new Cluster(startupNodes, options);\n    }\n    /**\n     * Get nodes with the specified role\n     */\n    nodes(role = \"all\") {\n        if (role !== \"all\" && role !== \"master\" && role !== \"slave\") {\n            throw new Error('Invalid role \"' + role + '\". Expected \"all\", \"master\" or \"slave\"');\n        }\n        return this.connectionPool.getNodes(role);\n    }\n    /**\n     * This is needed in order not to install a listener for each auto pipeline\n     *\n     * @ignore\n     */\n    delayUntilReady(callback) {\n        this._readyDelayedCallbacks.push(callback);\n    }\n    /**\n     * Get the number of commands queued in automatic pipelines.\n     *\n     * This is not available (and returns 0) until the cluster is connected and slots information have been received.\n     */\n    get autoPipelineQueueSize() {\n        let queued = 0;\n        for (const pipeline of this._autoPipelines.values()) {\n            queued += pipeline.length;\n        }\n        return queued;\n    }\n    /**\n     * Refresh the slot cache\n     *\n     * @ignore\n     */\n    refreshSlotsCache(callback) {\n        if (callback) {\n            this._refreshSlotsCacheCallbacks.push(callback);\n        }\n        if (this.isRefreshing) {\n            return;\n        }\n        this.isRefreshing = true;\n        const _this = this;\n        const wrapper = (error) => {\n            this.isRefreshing = false;\n            for (const callback of this._refreshSlotsCacheCallbacks) {\n                callback(error);\n            }\n            this._refreshSlotsCacheCallbacks = [];\n        };\n        const nodes = (0, utils_1.shuffle)(this.connectionPool.getNodes());\n        let lastNodeError = null;\n        function tryNode(index) {\n            if (index === nodes.length) {\n                const error = new ClusterAllFailedError_1.default(ClusterAllFailedError_1.default.defaultMessage, lastNodeError);\n                return wrapper(error);\n            }\n            const node = nodes[index];\n            const key = `${node.options.host}:${node.options.port}`;\n            debug(\"getting slot cache from %s\", key);\n            _this.getInfoFromNode(node, function (err) {\n                switch (_this.status) {\n                    case \"close\":\n                    case \"end\":\n                        return wrapper(new Error(\"Cluster is disconnected.\"));\n                    case \"disconnecting\":\n                        return wrapper(new Error(\"Cluster is disconnecting.\"));\n                }\n                if (err) {\n                    _this.emit(\"node error\", err, key);\n                    lastNodeError = err;\n                    tryNode(index + 1);\n                }\n                else {\n                    _this.emit(\"refresh\");\n                    wrapper();\n                }\n            });\n        }\n        tryNode(0);\n    }\n    /**\n     * @ignore\n     */\n    sendCommand(command, stream, node) {\n        if (this.status === \"wait\") {\n            this.connect().catch(utils_1.noop);\n        }\n        if (this.status === \"end\") {\n            command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n            return command.promise;\n        }\n        let to = this.options.scaleReads;\n        if (to !== \"master\") {\n            const isCommandReadOnly = command.isReadOnly ||\n                ((0, commands_1.exists)(command.name) && (0, commands_1.hasFlag)(command.name, \"readonly\"));\n            if (!isCommandReadOnly) {\n                to = \"master\";\n            }\n        }\n        let targetSlot = node ? node.slot : command.getSlot();\n        const ttl = {};\n        const _this = this;\n        if (!node && !REJECT_OVERWRITTEN_COMMANDS.has(command)) {\n            REJECT_OVERWRITTEN_COMMANDS.add(command);\n            const reject = command.reject;\n            command.reject = function (err) {\n                const partialTry = tryConnection.bind(null, true);\n                _this.handleError(err, ttl, {\n                    moved: function (slot, key) {\n                        debug(\"command %s is moved to %s\", command.name, key);\n                        targetSlot = Number(slot);\n                        if (_this.slots[slot]) {\n                            _this.slots[slot][0] = key;\n                        }\n                        else {\n                            _this.slots[slot] = [key];\n                        }\n                        _this._groupsBySlot[slot] =\n                            _this._groupsIds[_this.slots[slot].join(\";\")];\n                        _this.connectionPool.findOrCreate(_this.natMapper(key));\n                        tryConnection();\n                        debug(\"refreshing slot caches... (triggered by MOVED error)\");\n                        _this.refreshSlotsCache();\n                    },\n                    ask: function (slot, key) {\n                        debug(\"command %s is required to ask %s:%s\", command.name, key);\n                        const mapped = _this.natMapper(key);\n                        _this.connectionPool.findOrCreate(mapped);\n                        tryConnection(false, `${mapped.host}:${mapped.port}`);\n                    },\n                    tryagain: partialTry,\n                    clusterDown: partialTry,\n                    connectionClosed: partialTry,\n                    maxRedirections: function (redirectionError) {\n                        reject.call(command, redirectionError);\n                    },\n                    defaults: function () {\n                        reject.call(command, err);\n                    },\n                });\n            };\n        }\n        tryConnection();\n        function tryConnection(random, asking) {\n            if (_this.status === \"end\") {\n                command.reject(new redis_errors_1.AbortError(\"Cluster is ended.\"));\n                return;\n            }\n            let redis;\n            if (_this.status === \"ready\" || command.name === \"cluster\") {\n                if (node && node.redis) {\n                    redis = node.redis;\n                }\n                else if (Command_1.default.checkFlag(\"ENTER_SUBSCRIBER_MODE\", command.name) ||\n                    Command_1.default.checkFlag(\"EXIT_SUBSCRIBER_MODE\", command.name)) {\n                    if (_this.options.shardedSubscribers &&\n                        (command.name == \"ssubscribe\" || command.name == \"sunsubscribe\")) {\n                        const sub = _this.shardedSubscribers.getResponsibleSubscriber(targetSlot);\n                        if (!sub) {\n                            command.reject(new redis_errors_1.AbortError(`No sharded subscriber for slot: ${targetSlot}`));\n                            return;\n                        }\n                        let status = -1;\n                        if (command.name == \"ssubscribe\") {\n                            status = _this.shardedSubscribers.addChannels(command.getKeys());\n                        }\n                        if (command.name == \"sunsubscribe\") {\n                            status = _this.shardedSubscribers.removeChannels(command.getKeys());\n                        }\n                        if (status !== -1) {\n                            redis = sub.getInstance();\n                        }\n                        else {\n                            command.reject(new redis_errors_1.AbortError(\"Possible CROSSSLOT error: All channels must hash to the same slot\"));\n                        }\n                    }\n                    else {\n                        redis = _this.subscriber.getInstance();\n                    }\n                    if (!redis) {\n                        command.reject(new redis_errors_1.AbortError(\"No subscriber for the cluster\"));\n                        return;\n                    }\n                }\n                else {\n                    if (!random) {\n                        if (typeof targetSlot === \"number\" && _this.slots[targetSlot]) {\n                            const nodeKeys = _this.slots[targetSlot];\n                            if (typeof to === \"function\") {\n                                const nodes = nodeKeys.map(function (key) {\n                                    return _this.connectionPool.getInstanceByKey(key);\n                                });\n                                redis = to(nodes, command);\n                                if (Array.isArray(redis)) {\n                                    redis = (0, utils_1.sample)(redis);\n                                }\n                                if (!redis) {\n                                    redis = nodes[0];\n                                }\n                            }\n                            else {\n                                let key;\n                                if (to === \"all\") {\n                                    key = (0, utils_1.sample)(nodeKeys);\n                                }\n                                else if (to === \"slave\" && nodeKeys.length > 1) {\n                                    key = (0, utils_1.sample)(nodeKeys, 1);\n                                }\n                                else {\n                                    key = nodeKeys[0];\n                                }\n                                redis = _this.connectionPool.getInstanceByKey(key);\n                            }\n                        }\n                        if (asking) {\n                            redis = _this.connectionPool.getInstanceByKey(asking);\n                            redis.asking();\n                        }\n                    }\n                    if (!redis) {\n                        redis =\n                            (typeof to === \"function\"\n                                ? null\n                                : _this.connectionPool.getSampleInstance(to)) ||\n                                _this.connectionPool.getSampleInstance(\"all\");\n                    }\n                    if (redis &&\n                        !_this.options.enableOfflineQueue &&\n                        redis.status !== \"ready\" &&\n                        redis.status !== \"wait\") {\n                        command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n                        return;\n                    }\n                }\n                if (node && !node.redis) {\n                    node.redis = redis;\n                }\n            }\n            if (!redis && _this.options.enableOfflineQueue) {\n                _this.offlineQueue.push({\n                    command: command,\n                    stream: stream,\n                    node: node,\n                });\n                return;\n            }\n            if (!redis) {\n                command.reject(new Error(\"Cluster isn't ready and enableOfflineQueue options is false\"));\n                return;\n            }\n            redis.sendCommand(command, stream);\n        }\n        return command.promise;\n    }\n    sscanStream(key, options) {\n        return this.createScanStream(\"sscan\", { key, options });\n    }\n    sscanBufferStream(key, options) {\n        return this.createScanStream(\"sscanBuffer\", { key, options });\n    }\n    hscanStream(key, options) {\n        return this.createScanStream(\"hscan\", { key, options });\n    }\n    hscanBufferStream(key, options) {\n        return this.createScanStream(\"hscanBuffer\", { key, options });\n    }\n    zscanStream(key, options) {\n        return this.createScanStream(\"zscan\", { key, options });\n    }\n    zscanBufferStream(key, options) {\n        return this.createScanStream(\"zscanBuffer\", { key, options });\n    }\n    /**\n     * @ignore\n     */\n    handleError(error, ttl, handlers) {\n        if (typeof ttl.value === \"undefined\") {\n            ttl.value = this.options.maxRedirections;\n        }\n        else {\n            ttl.value -= 1;\n        }\n        if (ttl.value <= 0) {\n            handlers.maxRedirections(new Error(\"Too many Cluster redirections. Last error: \" + error));\n            return;\n        }\n        const errv = error.message.split(\" \");\n        if (errv[0] === \"MOVED\") {\n            const timeout = this.options.retryDelayOnMoved;\n            if (timeout && typeof timeout === \"number\") {\n                this.delayQueue.push(\"moved\", handlers.moved.bind(null, errv[1], errv[2]), { timeout });\n            }\n            else {\n                handlers.moved(errv[1], errv[2]);\n            }\n        }\n        else if (errv[0] === \"ASK\") {\n            handlers.ask(errv[1], errv[2]);\n        }\n        else if (errv[0] === \"TRYAGAIN\") {\n            this.delayQueue.push(\"tryagain\", handlers.tryagain, {\n                timeout: this.options.retryDelayOnTryAgain,\n            });\n        }\n        else if (errv[0] === \"CLUSTERDOWN\" &&\n            this.options.retryDelayOnClusterDown > 0) {\n            this.delayQueue.push(\"clusterdown\", handlers.connectionClosed, {\n                timeout: this.options.retryDelayOnClusterDown,\n                callback: this.refreshSlotsCache.bind(this),\n            });\n        }\n        else if (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG &&\n            this.options.retryDelayOnFailover > 0 &&\n            this.status === \"ready\") {\n            this.delayQueue.push(\"failover\", handlers.connectionClosed, {\n                timeout: this.options.retryDelayOnFailover,\n                callback: this.refreshSlotsCache.bind(this),\n            });\n        }\n        else {\n            handlers.defaults();\n        }\n    }\n    resetOfflineQueue() {\n        this.offlineQueue = new Deque();\n    }\n    clearNodesRefreshInterval() {\n        if (this.slotsTimer) {\n            clearTimeout(this.slotsTimer);\n            this.slotsTimer = null;\n        }\n    }\n    resetNodesRefreshInterval() {\n        if (this.slotsTimer || !this.options.slotsRefreshInterval) {\n            return;\n        }\n        const nextRound = () => {\n            this.slotsTimer = setTimeout(() => {\n                debug('refreshing slot caches... (triggered by \"slotsRefreshInterval\" option)');\n                this.refreshSlotsCache(() => {\n                    nextRound();\n                });\n            }, this.options.slotsRefreshInterval);\n        };\n        nextRound();\n    }\n    /**\n     * Change cluster instance's status\n     */\n    setStatus(status) {\n        debug(\"status: %s -> %s\", this.status || \"[empty]\", status);\n        this.status = status;\n        process.nextTick(() => {\n            this.emit(status);\n        });\n    }\n    /**\n     * Called when closed to check whether a reconnection should be made\n     */\n    handleCloseEvent(reason) {\n        var _a;\n        if (reason) {\n            debug(\"closed because %s\", reason);\n        }\n        let retryDelay;\n        if (!this.manuallyClosing &&\n            typeof this.options.clusterRetryStrategy === \"function\") {\n            retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason);\n        }\n        if (typeof retryDelay === \"number\") {\n            this.setStatus(\"reconnecting\");\n            this.reconnectTimeout = setTimeout(() => {\n                this.reconnectTimeout = null;\n                debug(\"Cluster is disconnected. Retrying after %dms\", retryDelay);\n                this.connect().catch(function (err) {\n                    debug(\"Got error %s when reconnecting. Ignoring...\", err);\n                });\n            }, retryDelay);\n        }\n        else {\n            if (this.options.shardedSubscribers) {\n                (_a = this.subscriberGroupEmitter) === null || _a === void 0 ? void 0 : _a.removeAllListeners();\n            }\n            this.setStatus(\"end\");\n            this.flushQueue(new Error(\"None of startup nodes is available\"));\n        }\n    }\n    /**\n     * Flush offline queue with error.\n     */\n    flushQueue(error) {\n        let item;\n        while ((item = this.offlineQueue.shift())) {\n            item.command.reject(error);\n        }\n    }\n    executeOfflineCommands() {\n        if (this.offlineQueue.length) {\n            debug(\"send %d commands in offline queue\", this.offlineQueue.length);\n            const offlineQueue = this.offlineQueue;\n            this.resetOfflineQueue();\n            let item;\n            while ((item = offlineQueue.shift())) {\n                this.sendCommand(item.command, item.stream, item.node);\n            }\n        }\n    }\n    natMapper(nodeKey) {\n        const key = typeof nodeKey === \"string\"\n            ? nodeKey\n            : `${nodeKey.host}:${nodeKey.port}`;\n        let mapped = null;\n        if (this.options.natMap && typeof this.options.natMap === \"function\") {\n            mapped = this.options.natMap(key);\n        }\n        else if (this.options.natMap && typeof this.options.natMap === \"object\") {\n            mapped = this.options.natMap[key];\n        }\n        if (mapped) {\n            debug(\"NAT mapping %s -> %O\", key, mapped);\n            return Object.assign({}, mapped);\n        }\n        return typeof nodeKey === \"string\"\n            ? (0, util_1.nodeKeyToRedisOptions)(nodeKey)\n            : nodeKey;\n    }\n    getInfoFromNode(redis, callback) {\n        if (!redis) {\n            return callback(new Error(\"Node is disconnected\"));\n        }\n        // Use a duplication of the connection to avoid\n        // timeouts when the connection is in the blocking\n        // mode (e.g. waiting for BLPOP).\n        const duplicatedConnection = redis.duplicate({\n            enableOfflineQueue: true,\n            enableReadyCheck: false,\n            retryStrategy: null,\n            connectionName: (0, util_1.getConnectionName)(\"refresher\", this.options.redisOptions && this.options.redisOptions.connectionName),\n        });\n        // Ignore error events since we will handle\n        // exceptions for the CLUSTER SLOTS command.\n        duplicatedConnection.on(\"error\", utils_1.noop);\n        duplicatedConnection.cluster(\"SLOTS\", (0, utils_1.timeout)((err, result) => {\n            duplicatedConnection.disconnect();\n            if (err) {\n                debug(\"error encountered running CLUSTER.SLOTS: %s\", err);\n                return callback(err);\n            }\n            if (this.status === \"disconnecting\" ||\n                this.status === \"close\" ||\n                this.status === \"end\") {\n                debug(\"ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s\", result.length, this.status);\n                callback();\n                return;\n            }\n            const nodes = [];\n            debug(\"cluster slots result count: %d\", result.length);\n            for (let i = 0; i < result.length; ++i) {\n                const items = result[i];\n                const slotRangeStart = items[0];\n                const slotRangeEnd = items[1];\n                const keys = [];\n                for (let j = 2; j < items.length; j++) {\n                    if (!items[j][0]) {\n                        continue;\n                    }\n                    const node = this.natMapper({\n                        host: items[j][0],\n                        port: items[j][1],\n                    });\n                    node.readOnly = j !== 2;\n                    nodes.push(node);\n                    keys.push(node.host + \":\" + node.port);\n                }\n                debug(\"cluster slots result [%d]: slots %d~%d served by %s\", i, slotRangeStart, slotRangeEnd, keys);\n                for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) {\n                    this.slots[slot] = keys;\n                }\n            }\n            // Assign to each node keys a numeric value to make autopipeline comparison faster.\n            this._groupsIds = Object.create(null);\n            let j = 0;\n            for (let i = 0; i < 16384; i++) {\n                const target = (this.slots[i] || []).join(\";\");\n                if (!target.length) {\n                    this._groupsBySlot[i] = undefined;\n                    continue;\n                }\n                if (!this._groupsIds[target]) {\n                    this._groupsIds[target] = ++j;\n                }\n                this._groupsBySlot[i] = this._groupsIds[target];\n            }\n            this.connectionPool.reset(nodes);\n            if (this.options.shardedSubscribers) {\n                this.shardedSubscribers\n                    .reset(this.slots, this.connectionPool.getNodes(\"all\"))\n                    .catch((err) => {\n                    // TODO should we emit an error event here?\n                    debug(\"Error while starting subscribers: %s\", err);\n                });\n            }\n            callback();\n        }, this.options.slotsRefreshTimeout));\n    }\n    invokeReadyDelayedCallbacks(err) {\n        for (const c of this._readyDelayedCallbacks) {\n            process.nextTick(c, err);\n        }\n        this._readyDelayedCallbacks = [];\n    }\n    /**\n     * Check whether Cluster is able to process commands\n     */\n    readyCheck(callback) {\n        this.cluster(\"INFO\", (err, res) => {\n            if (err) {\n                return callback(err);\n            }\n            if (typeof res !== \"string\") {\n                return callback();\n            }\n            let state;\n            const lines = res.split(\"\\r\\n\");\n            for (let i = 0; i < lines.length; ++i) {\n                const parts = lines[i].split(\":\");\n                if (parts[0] === \"cluster_state\") {\n                    state = parts[1];\n                    break;\n                }\n            }\n            if (state === \"fail\") {\n                debug(\"cluster state not ok (%s)\", state);\n                callback(null, state);\n            }\n            else {\n                callback();\n            }\n        });\n    }\n    resolveSrv(hostname) {\n        return new Promise((resolve, reject) => {\n            this.options.resolveSrv(hostname, (err, records) => {\n                if (err) {\n                    return reject(err);\n                }\n                const self = this, groupedRecords = (0, util_1.groupSrvRecords)(records), sortedKeys = Object.keys(groupedRecords).sort((a, b) => parseInt(a) - parseInt(b));\n                function tryFirstOne(err) {\n                    if (!sortedKeys.length) {\n                        return reject(err);\n                    }\n                    const key = sortedKeys[0], group = groupedRecords[key], record = (0, util_1.weightSrvRecords)(group);\n                    if (!group.records.length) {\n                        sortedKeys.shift();\n                    }\n                    self.dnsLookup(record.name).then((host) => resolve({\n                        host,\n                        port: record.port,\n                    }), tryFirstOne);\n                }\n                tryFirstOne();\n            });\n        });\n    }\n    dnsLookup(hostname) {\n        return new Promise((resolve, reject) => {\n            this.options.dnsLookup(hostname, (err, address) => {\n                if (err) {\n                    debug(\"failed to resolve hostname %s to IP: %s\", hostname, err.message);\n                    reject(err);\n                }\n                else {\n                    debug(\"resolved hostname %s to IP %s\", hostname, address);\n                    resolve(address);\n                }\n            });\n        });\n    }\n    /**\n     * Normalize startup nodes, and resolving hostnames to IPs.\n     *\n     * This process happens every time when #connect() is called since\n     * #startupNodes and DNS records may chanage.\n     */\n    async resolveStartupNodeHostnames() {\n        if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) {\n            throw new Error(\"`startupNodes` should contain at least one node.\");\n        }\n        const startupNodes = (0, util_1.normalizeNodeOptions)(this.startupNodes);\n        const hostnames = (0, util_1.getUniqueHostnamesFromOptions)(startupNodes);\n        if (hostnames.length === 0) {\n            return startupNodes;\n        }\n        const configs = await Promise.all(hostnames.map((this.options.useSRVRecords ? this.resolveSrv : this.dnsLookup).bind(this)));\n        const hostnameToConfig = (0, utils_1.zipMap)(hostnames, configs);\n        return startupNodes.map((node) => {\n            const config = hostnameToConfig.get(node.host);\n            if (!config) {\n                return node;\n            }\n            if (this.options.useSRVRecords) {\n                return Object.assign({}, node, config);\n            }\n            return Object.assign({}, node, { host: config });\n        });\n    }\n    createScanStream(command, { key, options = {} }) {\n        return new ScanStream_1.default({\n            objectMode: true,\n            key: key,\n            redis: this,\n            command: command,\n            ...options,\n        });\n    }\n    createShardedSubscriberGroup() {\n        this.subscriberGroupEmitter = new events_1.EventEmitter();\n        this.shardedSubscribers = new ClusterSubscriberGroup_1.default(this.subscriberGroupEmitter, this.options);\n        // Error handler used only for sharded-subscriber-triggered slots cache refreshes.\n        // Normal (non-subscriber) connections are created with lazyConnect: true and can\n        // become zombied. For sharded subscribers, a ClusterAllFailedError means\n        // we have lost all nodes from the subscriber perspective and must tear down.\n        const refreshSlotsCacheCallback = (err) => {\n            // Disconnect only when refreshing the slots cache fails with ClusterAllFailedError\n            if (err instanceof ClusterAllFailedError_1.default) {\n                this.disconnect(true);\n            }\n        };\n        this.subscriberGroupEmitter.on(\"-node\", (redis, nodeKey) => {\n            this.emit(\"-node\", redis, nodeKey);\n            this.refreshSlotsCache(refreshSlotsCacheCallback);\n        });\n        this.subscriberGroupEmitter.on(\"subscriberConnectFailed\", ({ delay, error }) => {\n            this.emit(\"error\", error);\n            setTimeout(() => {\n                this.refreshSlotsCache(refreshSlotsCacheCallback);\n            }, delay);\n        });\n        this.subscriberGroupEmitter.on(\"moved\", () => {\n            this.refreshSlotsCache(refreshSlotsCacheCallback);\n        });\n        this.subscriberGroupEmitter.on(\"-subscriber\", () => {\n            this.emit(\"-subscriber\");\n        });\n        this.subscriberGroupEmitter.on(\"+subscriber\", () => {\n            this.emit(\"+subscriber\");\n        });\n        this.subscriberGroupEmitter.on(\"nodeError\", (error, nodeKey) => {\n            this.emit(\"nodeError\", error, nodeKey);\n        });\n        this.subscriberGroupEmitter.on(\"subscribersReady\", () => {\n            this.emit(\"subscribersReady\");\n        });\n        for (const event of [\"smessage\", \"smessageBuffer\"]) {\n            this.subscriberGroupEmitter.on(event, (arg1, arg2, arg3) => {\n                this.emit(event, arg1, arg2, arg3);\n            });\n        }\n    }\n}\n(0, applyMixin_1.default)(Cluster, events_1.EventEmitter);\n(0, transaction_1.addTransactionSupport)(Cluster.prototype);\nexports.default = Cluster;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"../utils\");\nconst debug = (0, utils_1.Debug)(\"AbstractConnector\");\nclass AbstractConnector {\n    constructor(disconnectTimeout) {\n        this.connecting = false;\n        this.disconnectTimeout = disconnectTimeout;\n    }\n    check(info) {\n        return true;\n    }\n    disconnect() {\n        this.connecting = false;\n        if (this.stream) {\n            const stream = this.stream; // Make sure callbacks refer to the same instance\n            const timeout = setTimeout(() => {\n                debug(\"stream %s:%s still open, destroying it\", stream.remoteAddress, stream.remotePort);\n                stream.destroy();\n            }, this.disconnectTimeout);\n            stream.on(\"close\", () => clearTimeout(timeout));\n            stream.end();\n        }\n    }\n}\nexports.default = AbstractConnector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst net_1 = require(\"net\");\nconst tls_1 = require(\"tls\");\nconst utils_1 = require(\"../utils\");\nconst AbstractConnector_1 = require(\"./AbstractConnector\");\nclass StandaloneConnector extends AbstractConnector_1.default {\n    constructor(options) {\n        super(options.disconnectTimeout);\n        this.options = options;\n    }\n    connect(_) {\n        const { options } = this;\n        this.connecting = true;\n        let connectionOptions;\n        if (\"path\" in options && options.path) {\n            connectionOptions = {\n                path: options.path,\n            };\n        }\n        else {\n            connectionOptions = {};\n            if (\"port\" in options && options.port != null) {\n                connectionOptions.port = options.port;\n            }\n            if (\"host\" in options && options.host != null) {\n                connectionOptions.host = options.host;\n            }\n            if (\"family\" in options && options.family != null) {\n                connectionOptions.family = options.family;\n            }\n        }\n        if (options.tls) {\n            Object.assign(connectionOptions, options.tls);\n        }\n        // TODO:\n        // We use native Promise here since other Promise\n        // implementation may use different schedulers that\n        // cause issue when the stream is resolved in the\n        // next tick.\n        // Should use the provided promise in the next major\n        // version and do not connect before resolved.\n        return new Promise((resolve, reject) => {\n            process.nextTick(() => {\n                if (!this.connecting) {\n                    reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n                    return;\n                }\n                try {\n                    if (options.tls) {\n                        this.stream = (0, tls_1.connect)(connectionOptions);\n                    }\n                    else {\n                        this.stream = (0, net_1.createConnection)(connectionOptions);\n                    }\n                }\n                catch (err) {\n                    reject(err);\n                    return;\n                }\n                this.stream.once(\"error\", (err) => {\n                    this.firstError = err;\n                });\n                resolve(this.stream);\n            });\n        });\n    }\n}\nexports.default = StandaloneConnector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isSentinelEql(a, b) {\n    return ((a.host || \"127.0.0.1\") === (b.host || \"127.0.0.1\") &&\n        (a.port || 26379) === (b.port || 26379));\n}\nclass SentinelIterator {\n    constructor(sentinels) {\n        this.cursor = 0;\n        this.sentinels = sentinels.slice(0);\n    }\n    next() {\n        const done = this.cursor >= this.sentinels.length;\n        return { done, value: done ? undefined : this.sentinels[this.cursor++] };\n    }\n    reset(moveCurrentEndpointToFirst) {\n        if (moveCurrentEndpointToFirst &&\n            this.sentinels.length > 1 &&\n            this.cursor !== 1) {\n            this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1));\n        }\n        this.cursor = 0;\n    }\n    add(sentinel) {\n        for (let i = 0; i < this.sentinels.length; i++) {\n            if (isSentinelEql(sentinel, this.sentinels[i])) {\n                return false;\n            }\n        }\n        this.sentinels.push(sentinel);\n        return true;\n    }\n    toString() {\n        return `${JSON.stringify(this.sentinels)} @${this.cursor}`;\n    }\n}\nexports.default = SentinelIterator;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FailoverDetector = void 0;\nconst utils_1 = require(\"../../utils\");\nconst debug = (0, utils_1.Debug)(\"FailoverDetector\");\nconst CHANNEL_NAME = \"+switch-master\";\nclass FailoverDetector {\n    // sentinels can't be used for regular commands after this\n    constructor(connector, sentinels) {\n        this.isDisconnected = false;\n        this.connector = connector;\n        this.sentinels = sentinels;\n    }\n    cleanup() {\n        this.isDisconnected = true;\n        for (const sentinel of this.sentinels) {\n            sentinel.client.disconnect();\n        }\n    }\n    async subscribe() {\n        debug(\"Starting FailoverDetector\");\n        const promises = [];\n        for (const sentinel of this.sentinels) {\n            const promise = sentinel.client.subscribe(CHANNEL_NAME).catch((err) => {\n                debug(\"Failed to subscribe to failover messages on sentinel %s:%s (%s)\", sentinel.address.host || \"127.0.0.1\", sentinel.address.port || 26739, err.message);\n            });\n            promises.push(promise);\n            sentinel.client.on(\"message\", (channel) => {\n                if (!this.isDisconnected && channel === CHANNEL_NAME) {\n                    this.disconnect();\n                }\n            });\n        }\n        await Promise.all(promises);\n    }\n    disconnect() {\n        // Avoid disconnecting more than once per failover.\n        // A new FailoverDetector will be created after reconnecting.\n        this.isDisconnected = true;\n        debug(\"Failover detected, disconnecting\");\n        // Will call this.cleanup()\n        this.connector.disconnect();\n    }\n}\nexports.FailoverDetector = FailoverDetector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SentinelIterator = void 0;\nconst net_1 = require(\"net\");\nconst utils_1 = require(\"../../utils\");\nconst tls_1 = require(\"tls\");\nconst SentinelIterator_1 = require(\"./SentinelIterator\");\nexports.SentinelIterator = SentinelIterator_1.default;\nconst AbstractConnector_1 = require(\"../AbstractConnector\");\nconst Redis_1 = require(\"../../Redis\");\nconst FailoverDetector_1 = require(\"./FailoverDetector\");\nconst debug = (0, utils_1.Debug)(\"SentinelConnector\");\nclass SentinelConnector extends AbstractConnector_1.default {\n    constructor(options) {\n        super(options.disconnectTimeout);\n        this.options = options;\n        this.emitter = null;\n        this.failoverDetector = null;\n        if (!this.options.sentinels.length) {\n            throw new Error(\"Requires at least one sentinel to connect to.\");\n        }\n        if (!this.options.name) {\n            throw new Error(\"Requires the name of master.\");\n        }\n        this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels);\n    }\n    check(info) {\n        const roleMatches = !info.role || this.options.role === info.role;\n        if (!roleMatches) {\n            debug(\"role invalid, expected %s, but got %s\", this.options.role, info.role);\n            // Start from the next item.\n            // Note that `reset` will move the cursor to the previous element,\n            // so we advance two steps here.\n            this.sentinelIterator.next();\n            this.sentinelIterator.next();\n            this.sentinelIterator.reset(true);\n        }\n        return roleMatches;\n    }\n    disconnect() {\n        super.disconnect();\n        if (this.failoverDetector) {\n            this.failoverDetector.cleanup();\n        }\n    }\n    connect(eventEmitter) {\n        this.connecting = true;\n        this.retryAttempts = 0;\n        let lastError;\n        const connectToNext = async () => {\n            const endpoint = this.sentinelIterator.next();\n            if (endpoint.done) {\n                this.sentinelIterator.reset(false);\n                const retryDelay = typeof this.options.sentinelRetryStrategy === \"function\"\n                    ? this.options.sentinelRetryStrategy(++this.retryAttempts)\n                    : null;\n                let errorMsg = typeof retryDelay !== \"number\"\n                    ? \"All sentinels are unreachable and retry is disabled.\"\n                    : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`;\n                if (lastError) {\n                    errorMsg += ` Last error: ${lastError.message}`;\n                }\n                debug(errorMsg);\n                const error = new Error(errorMsg);\n                if (typeof retryDelay === \"number\") {\n                    eventEmitter(\"error\", error);\n                    await new Promise((resolve) => setTimeout(resolve, retryDelay));\n                    return connectToNext();\n                }\n                else {\n                    throw error;\n                }\n            }\n            let resolved = null;\n            let err = null;\n            try {\n                resolved = await this.resolve(endpoint.value);\n            }\n            catch (error) {\n                err = error;\n            }\n            if (!this.connecting) {\n                throw new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG);\n            }\n            const endpointAddress = endpoint.value.host + \":\" + endpoint.value.port;\n            if (resolved) {\n                debug(\"resolved: %s:%s from sentinel %s\", resolved.host, resolved.port, endpointAddress);\n                if (this.options.enableTLSForSentinelMode && this.options.tls) {\n                    Object.assign(resolved, this.options.tls);\n                    this.stream = (0, tls_1.connect)(resolved);\n                    this.stream.once(\"secureConnect\", this.initFailoverDetector.bind(this));\n                }\n                else {\n                    this.stream = (0, net_1.createConnection)(resolved);\n                    this.stream.once(\"connect\", this.initFailoverDetector.bind(this));\n                }\n                this.stream.once(\"error\", (err) => {\n                    this.firstError = err;\n                });\n                return this.stream;\n            }\n            else {\n                const errorMsg = err\n                    ? \"failed to connect to sentinel \" +\n                        endpointAddress +\n                        \" because \" +\n                        err.message\n                    : \"connected to sentinel \" +\n                        endpointAddress +\n                        \" successfully, but got an invalid reply: \" +\n                        resolved;\n                debug(errorMsg);\n                eventEmitter(\"sentinelError\", new Error(errorMsg));\n                if (err) {\n                    lastError = err;\n                }\n                return connectToNext();\n            }\n        };\n        return connectToNext();\n    }\n    async updateSentinels(client) {\n        if (!this.options.updateSentinels) {\n            return;\n        }\n        const result = await client.sentinel(\"sentinels\", this.options.name);\n        if (!Array.isArray(result)) {\n            return;\n        }\n        result\n            .map(utils_1.packObject)\n            .forEach((sentinel) => {\n            const flags = sentinel.flags ? sentinel.flags.split(\",\") : [];\n            if (flags.indexOf(\"disconnected\") === -1 &&\n                sentinel.ip &&\n                sentinel.port) {\n                const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel));\n                if (this.sentinelIterator.add(endpoint)) {\n                    debug(\"adding sentinel %s:%s\", endpoint.host, endpoint.port);\n                }\n            }\n        });\n        debug(\"Updated internal sentinels: %s\", this.sentinelIterator);\n    }\n    async resolveMaster(client) {\n        const result = await client.sentinel(\"get-master-addr-by-name\", this.options.name);\n        await this.updateSentinels(client);\n        return this.sentinelNatResolve(Array.isArray(result)\n            ? { host: result[0], port: Number(result[1]) }\n            : null);\n    }\n    async resolveSlave(client) {\n        const result = await client.sentinel(\"slaves\", this.options.name);\n        if (!Array.isArray(result)) {\n            return null;\n        }\n        const availableSlaves = result\n            .map(utils_1.packObject)\n            .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/));\n        return this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves));\n    }\n    sentinelNatResolve(item) {\n        if (!item || !this.options.natMap)\n            return item;\n        const key = `${item.host}:${item.port}`;\n        let result = item;\n        if (typeof this.options.natMap === \"function\") {\n            result = this.options.natMap(key) || item;\n        }\n        else if (typeof this.options.natMap === \"object\") {\n            result = this.options.natMap[key] || item;\n        }\n        return result;\n    }\n    connectToSentinel(endpoint, options) {\n        const redis = new Redis_1.default({\n            port: endpoint.port || 26379,\n            host: endpoint.host,\n            username: this.options.sentinelUsername || null,\n            password: this.options.sentinelPassword || null,\n            family: endpoint.family ||\n                // @ts-expect-error\n                (\"path\" in this.options && this.options.path\n                    ? undefined\n                    : // @ts-expect-error\n                        this.options.family),\n            tls: this.options.sentinelTLS,\n            retryStrategy: null,\n            enableReadyCheck: false,\n            connectTimeout: this.options.connectTimeout,\n            commandTimeout: this.options.sentinelCommandTimeout,\n            ...options,\n        });\n        // @ts-expect-error\n        return redis;\n    }\n    async resolve(endpoint) {\n        const client = this.connectToSentinel(endpoint);\n        // ignore the errors since resolve* methods will handle them\n        client.on(\"error\", noop);\n        try {\n            if (this.options.role === \"slave\") {\n                return await this.resolveSlave(client);\n            }\n            else {\n                return await this.resolveMaster(client);\n            }\n        }\n        finally {\n            client.disconnect();\n        }\n    }\n    async initFailoverDetector() {\n        var _a;\n        if (!this.options.failoverDetector) {\n            return;\n        }\n        // Move the current sentinel to the first position\n        this.sentinelIterator.reset(true);\n        const sentinels = [];\n        // In case of a large amount of sentinels, limit the number of concurrent connections\n        while (sentinels.length < this.options.sentinelMaxConnections) {\n            const { done, value } = this.sentinelIterator.next();\n            if (done) {\n                break;\n            }\n            const client = this.connectToSentinel(value, {\n                lazyConnect: true,\n                retryStrategy: this.options.sentinelReconnectStrategy,\n            });\n            client.on(\"reconnecting\", () => {\n                var _a;\n                // Tests listen to this event\n                (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit(\"sentinelReconnecting\");\n            });\n            sentinels.push({ address: value, client });\n        }\n        this.sentinelIterator.reset(false);\n        if (this.failoverDetector) {\n            // Clean up previous detector\n            this.failoverDetector.cleanup();\n        }\n        this.failoverDetector = new FailoverDetector_1.FailoverDetector(this, sentinels);\n        await this.failoverDetector.subscribe();\n        // Tests listen to this event\n        (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit(\"failoverSubscribed\");\n    }\n}\nexports.default = SentinelConnector;\nfunction selectPreferredSentinel(availableSlaves, preferredSlaves) {\n    if (availableSlaves.length === 0) {\n        return null;\n    }\n    let selectedSlave;\n    if (typeof preferredSlaves === \"function\") {\n        selectedSlave = preferredSlaves(availableSlaves);\n    }\n    else if (preferredSlaves !== null && typeof preferredSlaves === \"object\") {\n        const preferredSlavesArray = Array.isArray(preferredSlaves)\n            ? preferredSlaves\n            : [preferredSlaves];\n        // sort by priority\n        preferredSlavesArray.sort((a, b) => {\n            // default the priority to 1\n            if (!a.prio) {\n                a.prio = 1;\n            }\n            if (!b.prio) {\n                b.prio = 1;\n            }\n            // lowest priority first\n            if (a.prio < b.prio) {\n                return -1;\n            }\n            if (a.prio > b.prio) {\n                return 1;\n            }\n            return 0;\n        });\n        // loop over preferred slaves and return the first match\n        for (let p = 0; p < preferredSlavesArray.length; p++) {\n            for (let a = 0; a < availableSlaves.length; a++) {\n                const slave = availableSlaves[a];\n                if (slave.ip === preferredSlavesArray[p].ip) {\n                    if (slave.port === preferredSlavesArray[p].port) {\n                        selectedSlave = slave;\n                        break;\n                    }\n                }\n            }\n            if (selectedSlave) {\n                break;\n            }\n        }\n    }\n    // if none of the preferred slaves are available, a random available slave is returned\n    if (!selectedSlave) {\n        selectedSlave = (0, utils_1.sample)(availableSlaves);\n    }\n    return addressResponseToAddress(selectedSlave);\n}\nfunction addressResponseToAddress(input) {\n    return { host: input.ip, port: Number(input.port) };\n}\nfunction noop() { }\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SentinelConnector = exports.StandaloneConnector = void 0;\nconst StandaloneConnector_1 = require(\"./StandaloneConnector\");\nexports.StandaloneConnector = StandaloneConnector_1.default;\nconst SentinelConnector_1 = require(\"./SentinelConnector\");\nexports.SentinelConnector = SentinelConnector_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst redis_errors_1 = require(\"redis-errors\");\nclass MaxRetriesPerRequestError extends redis_errors_1.AbortError {\n    constructor(maxRetriesPerRequest) {\n        const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to \"maxRetriesPerRequest\" option for details.`;\n        super(message);\n        Error.captureStackTrace(this, this.constructor);\n    }\n    get name() {\n        return this.constructor.name;\n    }\n}\nexports.default = MaxRetriesPerRequestError;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MaxRetriesPerRequestError = void 0;\nconst MaxRetriesPerRequestError_1 = require(\"./MaxRetriesPerRequestError\");\nexports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default;\n","'use strict'\n\nconst Buffer = require('buffer').Buffer\nconst StringDecoder = require('string_decoder').StringDecoder\nconst decoder = new StringDecoder()\nconst errors = require('redis-errors')\nconst ReplyError = errors.ReplyError\nconst ParserError = errors.ParserError\nvar bufferPool = Buffer.allocUnsafe(32 * 1024)\nvar bufferOffset = 0\nvar interval = null\nvar counter = 0\nvar notDecreased = 0\n\n/**\n * Used for integer numbers only\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|number}\n */\nfunction parseSimpleNumbers (parser) {\n  const length = parser.buffer.length - 1\n  var offset = parser.offset\n  var number = 0\n  var sign = 1\n\n  if (parser.buffer[offset] === 45) {\n    sign = -1\n    offset++\n  }\n\n  while (offset < length) {\n    const c1 = parser.buffer[offset++]\n    if (c1 === 13) { // \\r\\n\n      parser.offset = offset + 1\n      return sign * number\n    }\n    number = (number * 10) + (c1 - 48)\n  }\n}\n\n/**\n * Used for integer numbers in case of the returnNumbers option\n *\n * Reading the string as parts of n SMI is more efficient than\n * using a string directly.\n *\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|string}\n */\nfunction parseStringNumbers (parser) {\n  const length = parser.buffer.length - 1\n  var offset = parser.offset\n  var number = 0\n  var res = ''\n\n  if (parser.buffer[offset] === 45) {\n    res += '-'\n    offset++\n  }\n\n  while (offset < length) {\n    var c1 = parser.buffer[offset++]\n    if (c1 === 13) { // \\r\\n\n      parser.offset = offset + 1\n      if (number !== 0) {\n        res += number\n      }\n      return res\n    } else if (number > 429496728) {\n      res += (number * 10) + (c1 - 48)\n      number = 0\n    } else if (c1 === 48 && number === 0) {\n      res += 0\n    } else {\n      number = (number * 10) + (c1 - 48)\n    }\n  }\n}\n\n/**\n * Parse a '+' redis simple string response but forward the offsets\n * onto convertBufferRange to generate a string.\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|string|Buffer}\n */\nfunction parseSimpleString (parser) {\n  const start = parser.offset\n  const buffer = parser.buffer\n  const length = buffer.length - 1\n  var offset = start\n\n  while (offset < length) {\n    if (buffer[offset++] === 13) { // \\r\\n\n      parser.offset = offset + 1\n      if (parser.optionReturnBuffers === true) {\n        return parser.buffer.slice(start, offset - 1)\n      }\n      return parser.buffer.toString('utf8', start, offset - 1)\n    }\n  }\n}\n\n/**\n * Returns the read length\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|number}\n */\nfunction parseLength (parser) {\n  const length = parser.buffer.length - 1\n  var offset = parser.offset\n  var number = 0\n\n  while (offset < length) {\n    const c1 = parser.buffer[offset++]\n    if (c1 === 13) {\n      parser.offset = offset + 1\n      return number\n    }\n    number = (number * 10) + (c1 - 48)\n  }\n}\n\n/**\n * Parse a ':' redis integer response\n *\n * If stringNumbers is activated the parser always returns numbers as string\n * This is important for big numbers (number > Math.pow(2, 53)) as js numbers\n * are 64bit floating point numbers with reduced precision\n *\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|number|string}\n */\nfunction parseInteger (parser) {\n  if (parser.optionStringNumbers === true) {\n    return parseStringNumbers(parser)\n  }\n  return parseSimpleNumbers(parser)\n}\n\n/**\n * Parse a '$' redis bulk string response\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|null|string}\n */\nfunction parseBulkString (parser) {\n  const length = parseLength(parser)\n  if (length === undefined) {\n    return\n  }\n  if (length < 0) {\n    return null\n  }\n  const offset = parser.offset + length\n  if (offset + 2 > parser.buffer.length) {\n    parser.bigStrSize = offset + 2\n    parser.totalChunkSize = parser.buffer.length\n    parser.bufferCache.push(parser.buffer)\n    return\n  }\n  const start = parser.offset\n  parser.offset = offset + 2\n  if (parser.optionReturnBuffers === true) {\n    return parser.buffer.slice(start, offset)\n  }\n  return parser.buffer.toString('utf8', start, offset)\n}\n\n/**\n * Parse a '-' redis error response\n * @param {JavascriptRedisParser} parser\n * @returns {ReplyError}\n */\nfunction parseError (parser) {\n  var string = parseSimpleString(parser)\n  if (string !== undefined) {\n    if (parser.optionReturnBuffers === true) {\n      string = string.toString()\n    }\n    return new ReplyError(string)\n  }\n}\n\n/**\n * Parsing error handler, resets parser buffer\n * @param {JavascriptRedisParser} parser\n * @param {number} type\n * @returns {undefined}\n */\nfunction handleError (parser, type) {\n  const err = new ParserError(\n    'Protocol error, got ' + JSON.stringify(String.fromCharCode(type)) + ' as reply type byte',\n    JSON.stringify(parser.buffer),\n    parser.offset\n  )\n  parser.buffer = null\n  parser.returnFatalError(err)\n}\n\n/**\n * Parse a '*' redis array response\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|null|any[]}\n */\nfunction parseArray (parser) {\n  const length = parseLength(parser)\n  if (length === undefined) {\n    return\n  }\n  if (length < 0) {\n    return null\n  }\n  const responses = new Array(length)\n  return parseArrayElements(parser, responses, 0)\n}\n\n/**\n * Push a partly parsed array to the stack\n *\n * @param {JavascriptRedisParser} parser\n * @param {any[]} array\n * @param {number} pos\n * @returns {undefined}\n */\nfunction pushArrayCache (parser, array, pos) {\n  parser.arrayCache.push(array)\n  parser.arrayPos.push(pos)\n}\n\n/**\n * Parse chunked redis array response\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|any[]}\n */\nfunction parseArrayChunks (parser) {\n  const tmp = parser.arrayCache.pop()\n  var pos = parser.arrayPos.pop()\n  if (parser.arrayCache.length) {\n    const res = parseArrayChunks(parser)\n    if (res === undefined) {\n      pushArrayCache(parser, tmp, pos)\n      return\n    }\n    tmp[pos++] = res\n  }\n  return parseArrayElements(parser, tmp, pos)\n}\n\n/**\n * Parse redis array response elements\n * @param {JavascriptRedisParser} parser\n * @param {Array} responses\n * @param {number} i\n * @returns {undefined|null|any[]}\n */\nfunction parseArrayElements (parser, responses, i) {\n  const bufferLength = parser.buffer.length\n  while (i < responses.length) {\n    const offset = parser.offset\n    if (parser.offset >= bufferLength) {\n      pushArrayCache(parser, responses, i)\n      return\n    }\n    const response = parseType(parser, parser.buffer[parser.offset++])\n    if (response === undefined) {\n      if (!(parser.arrayCache.length || parser.bufferCache.length)) {\n        parser.offset = offset\n      }\n      pushArrayCache(parser, responses, i)\n      return\n    }\n    responses[i] = response\n    i++\n  }\n\n  return responses\n}\n\n/**\n * Called the appropriate parser for the specified type.\n *\n * 36: $\n * 43: +\n * 42: *\n * 58: :\n * 45: -\n *\n * @param {JavascriptRedisParser} parser\n * @param {number} type\n * @returns {*}\n */\nfunction parseType (parser, type) {\n  switch (type) {\n    case 36:\n      return parseBulkString(parser)\n    case 43:\n      return parseSimpleString(parser)\n    case 42:\n      return parseArray(parser)\n    case 58:\n      return parseInteger(parser)\n    case 45:\n      return parseError(parser)\n    default:\n      return handleError(parser, type)\n  }\n}\n\n/**\n * Decrease the bufferPool size over time\n *\n * Balance between increasing and decreasing the bufferPool.\n * Decrease the bufferPool by 10% by removing the first 10% of the current pool.\n * @returns {undefined}\n */\nfunction decreaseBufferPool () {\n  if (bufferPool.length > 50 * 1024) {\n    if (counter === 1 || notDecreased > counter * 2) {\n      const minSliceLen = Math.floor(bufferPool.length / 10)\n      const sliceLength = minSliceLen < bufferOffset\n        ? bufferOffset\n        : minSliceLen\n      bufferOffset = 0\n      bufferPool = bufferPool.slice(sliceLength, bufferPool.length)\n    } else {\n      notDecreased++\n      counter--\n    }\n  } else {\n    clearInterval(interval)\n    counter = 0\n    notDecreased = 0\n    interval = null\n  }\n}\n\n/**\n * Check if the requested size fits in the current bufferPool.\n * If it does not, reset and increase the bufferPool accordingly.\n *\n * @param {number} length\n * @returns {undefined}\n */\nfunction resizeBuffer (length) {\n  if (bufferPool.length < length + bufferOffset) {\n    const multiplier = length > 1024 * 1024 * 75 ? 2 : 3\n    if (bufferOffset > 1024 * 1024 * 111) {\n      bufferOffset = 1024 * 1024 * 50\n    }\n    bufferPool = Buffer.allocUnsafe(length * multiplier + bufferOffset)\n    bufferOffset = 0\n    counter++\n    if (interval === null) {\n      interval = setInterval(decreaseBufferPool, 50)\n    }\n  }\n}\n\n/**\n * Concat a bulk string containing multiple chunks\n *\n * Notes:\n * 1) The first chunk might contain the whole bulk string including the \\r\n * 2) We are only safe to fully add up elements that are neither the first nor any of the last two elements\n *\n * @param {JavascriptRedisParser} parser\n * @returns {String}\n */\nfunction concatBulkString (parser) {\n  const list = parser.bufferCache\n  const oldOffset = parser.offset\n  var chunks = list.length\n  var offset = parser.bigStrSize - parser.totalChunkSize\n  parser.offset = offset\n  if (offset <= 2) {\n    if (chunks === 2) {\n      return list[0].toString('utf8', oldOffset, list[0].length + offset - 2)\n    }\n    chunks--\n    offset = list[list.length - 2].length + offset\n  }\n  var res = decoder.write(list[0].slice(oldOffset))\n  for (var i = 1; i < chunks - 1; i++) {\n    res += decoder.write(list[i])\n  }\n  res += decoder.end(list[i].slice(0, offset - 2))\n  return res\n}\n\n/**\n * Concat the collected chunks from parser.bufferCache.\n *\n * Increases the bufferPool size beforehand if necessary.\n *\n * @param {JavascriptRedisParser} parser\n * @returns {Buffer}\n */\nfunction concatBulkBuffer (parser) {\n  const list = parser.bufferCache\n  const oldOffset = parser.offset\n  const length = parser.bigStrSize - oldOffset - 2\n  var chunks = list.length\n  var offset = parser.bigStrSize - parser.totalChunkSize\n  parser.offset = offset\n  if (offset <= 2) {\n    if (chunks === 2) {\n      return list[0].slice(oldOffset, list[0].length + offset - 2)\n    }\n    chunks--\n    offset = list[list.length - 2].length + offset\n  }\n  resizeBuffer(length)\n  const start = bufferOffset\n  list[0].copy(bufferPool, start, oldOffset, list[0].length)\n  bufferOffset += list[0].length - oldOffset\n  for (var i = 1; i < chunks - 1; i++) {\n    list[i].copy(bufferPool, bufferOffset)\n    bufferOffset += list[i].length\n  }\n  list[i].copy(bufferPool, bufferOffset, 0, offset - 2)\n  bufferOffset += offset - 2\n  return bufferPool.slice(start, bufferOffset)\n}\n\nclass JavascriptRedisParser {\n  /**\n   * Javascript Redis Parser constructor\n   * @param {{returnError: Function, returnReply: Function, returnFatalError?: Function, returnBuffers: boolean, stringNumbers: boolean }} options\n   * @constructor\n   */\n  constructor (options) {\n    if (!options) {\n      throw new TypeError('Options are mandatory.')\n    }\n    if (typeof options.returnError !== 'function' || typeof options.returnReply !== 'function') {\n      throw new TypeError('The returnReply and returnError options have to be functions.')\n    }\n    this.setReturnBuffers(!!options.returnBuffers)\n    this.setStringNumbers(!!options.stringNumbers)\n    this.returnError = options.returnError\n    this.returnFatalError = options.returnFatalError || options.returnError\n    this.returnReply = options.returnReply\n    this.reset()\n  }\n\n  /**\n   * Reset the parser values to the initial state\n   *\n   * @returns {undefined}\n   */\n  reset () {\n    this.offset = 0\n    this.buffer = null\n    this.bigStrSize = 0\n    this.totalChunkSize = 0\n    this.bufferCache = []\n    this.arrayCache = []\n    this.arrayPos = []\n  }\n\n  /**\n   * Set the returnBuffers option\n   *\n   * @param {boolean} returnBuffers\n   * @returns {undefined}\n   */\n  setReturnBuffers (returnBuffers) {\n    if (typeof returnBuffers !== 'boolean') {\n      throw new TypeError('The returnBuffers argument has to be a boolean')\n    }\n    this.optionReturnBuffers = returnBuffers\n  }\n\n  /**\n   * Set the stringNumbers option\n   *\n   * @param {boolean} stringNumbers\n   * @returns {undefined}\n   */\n  setStringNumbers (stringNumbers) {\n    if (typeof stringNumbers !== 'boolean') {\n      throw new TypeError('The stringNumbers argument has to be a boolean')\n    }\n    this.optionStringNumbers = stringNumbers\n  }\n\n  /**\n   * Parse the redis buffer\n   * @param {Buffer} buffer\n   * @returns {undefined}\n   */\n  execute (buffer) {\n    if (this.buffer === null) {\n      this.buffer = buffer\n      this.offset = 0\n    } else if (this.bigStrSize === 0) {\n      const oldLength = this.buffer.length\n      const remainingLength = oldLength - this.offset\n      const newBuffer = Buffer.allocUnsafe(remainingLength + buffer.length)\n      this.buffer.copy(newBuffer, 0, this.offset, oldLength)\n      buffer.copy(newBuffer, remainingLength, 0, buffer.length)\n      this.buffer = newBuffer\n      this.offset = 0\n      if (this.arrayCache.length) {\n        const arr = parseArrayChunks(this)\n        if (arr === undefined) {\n          return\n        }\n        this.returnReply(arr)\n      }\n    } else if (this.totalChunkSize + buffer.length >= this.bigStrSize) {\n      this.bufferCache.push(buffer)\n      var tmp = this.optionReturnBuffers ? concatBulkBuffer(this) : concatBulkString(this)\n      this.bigStrSize = 0\n      this.bufferCache = []\n      this.buffer = buffer\n      if (this.arrayCache.length) {\n        this.arrayCache[0][this.arrayPos[0]++] = tmp\n        tmp = parseArrayChunks(this)\n        if (tmp === undefined) {\n          return\n        }\n      }\n      this.returnReply(tmp)\n    } else {\n      this.bufferCache.push(buffer)\n      this.totalChunkSize += buffer.length\n      return\n    }\n\n    while (this.offset < this.buffer.length) {\n      const offset = this.offset\n      const type = this.buffer[this.offset++]\n      const response = parseType(this, type)\n      if (response === undefined) {\n        if (!(this.arrayCache.length || this.bufferCache.length)) {\n          this.offset = offset\n        }\n        return\n      }\n\n      if (type === 45) {\n        this.returnError(response)\n      } else {\n        this.returnReply(response)\n      }\n    }\n\n    this.buffer = null\n  }\n}\n\nmodule.exports = JavascriptRedisParser\n","'use strict'\n\nmodule.exports = require('./lib/parser')\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Tiny class to simplify dealing with subscription set\n */\nclass SubscriptionSet {\n    constructor() {\n        this.set = {\n            subscribe: {},\n            psubscribe: {},\n            ssubscribe: {},\n        };\n    }\n    add(set, channel) {\n        this.set[mapSet(set)][channel] = true;\n    }\n    del(set, channel) {\n        delete this.set[mapSet(set)][channel];\n    }\n    channels(set) {\n        return Object.keys(this.set[mapSet(set)]);\n    }\n    isEmpty() {\n        return (this.channels(\"subscribe\").length === 0 &&\n            this.channels(\"psubscribe\").length === 0 &&\n            this.channels(\"ssubscribe\").length === 0);\n    }\n}\nexports.default = SubscriptionSet;\nfunction mapSet(set) {\n    if (set === \"unsubscribe\") {\n        return \"subscribe\";\n    }\n    if (set === \"punsubscribe\") {\n        return \"psubscribe\";\n    }\n    if (set === \"sunsubscribe\") {\n        return \"ssubscribe\";\n    }\n    return set;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Command_1 = require(\"./Command\");\nconst utils_1 = require(\"./utils\");\nconst RedisParser = require(\"redis-parser\");\nconst SubscriptionSet_1 = require(\"./SubscriptionSet\");\nconst debug = (0, utils_1.Debug)(\"dataHandler\");\nclass DataHandler {\n    constructor(redis, parserOptions) {\n        this.redis = redis;\n        const parser = new RedisParser({\n            stringNumbers: parserOptions.stringNumbers,\n            returnBuffers: true,\n            returnError: (err) => {\n                this.returnError(err);\n            },\n            returnFatalError: (err) => {\n                this.returnFatalError(err);\n            },\n            returnReply: (reply) => {\n                this.returnReply(reply);\n            },\n        });\n        // prependListener ensures the parser receives and processes data before socket timeout checks are performed\n        redis.stream.prependListener(\"data\", (data) => {\n            parser.execute(data);\n        });\n        // prependListener() doesn't enable flowing mode automatically - we need to resume the stream manually\n        redis.stream.resume();\n    }\n    returnFatalError(err) {\n        err.message += \". Please report this.\";\n        this.redis.recoverFromFatalError(err, err, { offlineQueue: false });\n    }\n    returnError(err) {\n        const item = this.shiftCommand(err);\n        if (!item) {\n            return;\n        }\n        err.command = {\n            name: item.command.name,\n            args: item.command.args,\n        };\n        if (item.command.name == \"ssubscribe\" && err.message.includes(\"MOVED\")) {\n            this.redis.emit(\"moved\");\n            return;\n        }\n        this.redis.handleReconnection(err, item);\n    }\n    returnReply(reply) {\n        if (this.handleMonitorReply(reply)) {\n            return;\n        }\n        if (this.handleSubscriberReply(reply)) {\n            return;\n        }\n        const item = this.shiftCommand(reply);\n        if (!item) {\n            return;\n        }\n        if (Command_1.default.checkFlag(\"ENTER_SUBSCRIBER_MODE\", item.command.name)) {\n            this.redis.condition.subscriber = new SubscriptionSet_1.default();\n            this.redis.condition.subscriber.add(item.command.name, reply[1].toString());\n            if (!fillSubCommand(item.command, reply[2])) {\n                this.redis.commandQueue.unshift(item);\n            }\n        }\n        else if (Command_1.default.checkFlag(\"EXIT_SUBSCRIBER_MODE\", item.command.name)) {\n            if (!fillUnsubCommand(item.command, reply[2])) {\n                this.redis.commandQueue.unshift(item);\n            }\n        }\n        else {\n            item.command.resolve(reply);\n        }\n    }\n    handleSubscriberReply(reply) {\n        if (!this.redis.condition.subscriber) {\n            return false;\n        }\n        const replyType = Array.isArray(reply) ? reply[0].toString() : null;\n        debug('receive reply \"%s\" in subscriber mode', replyType);\n        switch (replyType) {\n            case \"message\":\n                if (this.redis.listeners(\"message\").length > 0) {\n                    // Check if there're listeners to avoid unnecessary `toString()`.\n                    this.redis.emit(\"message\", reply[1].toString(), reply[2] ? reply[2].toString() : \"\");\n                }\n                this.redis.emit(\"messageBuffer\", reply[1], reply[2]);\n                break;\n            case \"pmessage\": {\n                const pattern = reply[1].toString();\n                if (this.redis.listeners(\"pmessage\").length > 0) {\n                    this.redis.emit(\"pmessage\", pattern, reply[2].toString(), reply[3].toString());\n                }\n                this.redis.emit(\"pmessageBuffer\", pattern, reply[2], reply[3]);\n                break;\n            }\n            case \"smessage\": {\n                if (this.redis.listeners(\"smessage\").length > 0) {\n                    this.redis.emit(\"smessage\", reply[1].toString(), reply[2] ? reply[2].toString() : \"\");\n                }\n                this.redis.emit(\"smessageBuffer\", reply[1], reply[2]);\n                break;\n            }\n            case \"ssubscribe\":\n            case \"subscribe\":\n            case \"psubscribe\": {\n                const channel = reply[1].toString();\n                this.redis.condition.subscriber.add(replyType, channel);\n                const item = this.shiftCommand(reply);\n                if (!item) {\n                    return;\n                }\n                if (!fillSubCommand(item.command, reply[2])) {\n                    this.redis.commandQueue.unshift(item);\n                }\n                break;\n            }\n            case \"sunsubscribe\":\n            case \"unsubscribe\":\n            case \"punsubscribe\": {\n                const channel = reply[1] ? reply[1].toString() : null;\n                if (channel) {\n                    this.redis.condition.subscriber.del(replyType, channel);\n                }\n                const count = reply[2];\n                if (Number(count) === 0) {\n                    this.redis.condition.subscriber = false;\n                }\n                const item = this.shiftCommand(reply);\n                if (!item) {\n                    return;\n                }\n                if (!fillUnsubCommand(item.command, count)) {\n                    this.redis.commandQueue.unshift(item);\n                }\n                break;\n            }\n            default: {\n                const item = this.shiftCommand(reply);\n                if (!item) {\n                    return;\n                }\n                item.command.resolve(reply);\n            }\n        }\n        return true;\n    }\n    handleMonitorReply(reply) {\n        if (this.redis.status !== \"monitoring\") {\n            return false;\n        }\n        const replyStr = reply.toString();\n        if (replyStr === \"OK\") {\n            // Valid commands in the monitoring mode are AUTH and MONITOR,\n            // both of which always reply with 'OK'.\n            // So if we got an 'OK', we can make certain that\n            // the reply is made to AUTH & MONITOR.\n            return false;\n        }\n        // Since commands sent in the monitoring mode will trigger an exception,\n        // any replies we received in the monitoring mode should consider to be\n        // realtime monitor data instead of result of commands.\n        const len = replyStr.indexOf(\" \");\n        const timestamp = replyStr.slice(0, len);\n        const argIndex = replyStr.indexOf('\"');\n        const args = replyStr\n            .slice(argIndex + 1, -1)\n            .split('\" \"')\n            .map((elem) => elem.replace(/\\\\\"/g, '\"'));\n        const dbAndSource = replyStr.slice(len + 2, argIndex - 2).split(\" \");\n        this.redis.emit(\"monitor\", timestamp, args, dbAndSource[1], dbAndSource[0]);\n        return true;\n    }\n    shiftCommand(reply) {\n        const item = this.redis.commandQueue.shift();\n        if (!item) {\n            const message = \"Command queue state error. If you can reproduce this, please report it.\";\n            const error = new Error(message +\n                (reply instanceof Error\n                    ? ` Last error: ${reply.message}`\n                    : ` Last reply: ${reply.toString()}`));\n            this.redis.emit(\"error\", error);\n            return null;\n        }\n        return item;\n    }\n}\nexports.default = DataHandler;\nconst remainingRepliesMap = new WeakMap();\nfunction fillSubCommand(command, count) {\n    let remainingReplies = remainingRepliesMap.has(command)\n        ? remainingRepliesMap.get(command)\n        : command.args.length;\n    remainingReplies -= 1;\n    if (remainingReplies <= 0) {\n        command.resolve(count);\n        remainingRepliesMap.delete(command);\n        return true;\n    }\n    remainingRepliesMap.set(command, remainingReplies);\n    return false;\n}\nfunction fillUnsubCommand(command, count) {\n    let remainingReplies = remainingRepliesMap.has(command)\n        ? remainingRepliesMap.get(command)\n        : command.args.length;\n    if (remainingReplies === 0) {\n        if (Number(count) === 0) {\n            remainingRepliesMap.delete(command);\n            command.resolve(count);\n            return true;\n        }\n        return false;\n    }\n    remainingReplies -= 1;\n    if (remainingReplies <= 0) {\n        command.resolve(count);\n        return true;\n    }\n    remainingRepliesMap.set(command, remainingReplies);\n    return false;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.readyHandler = exports.errorHandler = exports.closeHandler = exports.connectHandler = void 0;\nconst redis_errors_1 = require(\"redis-errors\");\nconst Command_1 = require(\"../Command\");\nconst errors_1 = require(\"../errors\");\nconst utils_1 = require(\"../utils\");\nconst DataHandler_1 = require(\"../DataHandler\");\nconst debug = (0, utils_1.Debug)(\"connection\");\nfunction connectHandler(self) {\n    return function () {\n        var _a;\n        self.setStatus(\"connect\");\n        self.resetCommandQueue();\n        // AUTH command should be processed before any other commands\n        let flushed = false;\n        const { connectionEpoch } = self;\n        if (self.condition.auth) {\n            self.auth(self.condition.auth, function (err) {\n                if (connectionEpoch !== self.connectionEpoch) {\n                    return;\n                }\n                if (err) {\n                    if (err.message.indexOf(\"no password is set\") !== -1) {\n                        console.warn(\"[WARN] Redis server does not require a password, but a password was supplied.\");\n                    }\n                    else if (err.message.indexOf(\"without any password configured for the default user\") !== -1) {\n                        console.warn(\"[WARN] This Redis server's `default` user does not require a password, but a password was supplied\");\n                    }\n                    else if (err.message.indexOf(\"wrong number of arguments for 'auth' command\") !== -1) {\n                        console.warn(`[ERROR] The server returned \"wrong number of arguments for 'auth' command\". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`);\n                    }\n                    else {\n                        flushed = true;\n                        self.recoverFromFatalError(err, err);\n                    }\n                }\n            });\n        }\n        if (self.condition.select) {\n            self.select(self.condition.select).catch((err) => {\n                // If the node is in cluster mode, select is disallowed.\n                // In this case, reconnect won't help.\n                self.silentEmit(\"error\", err);\n            });\n        }\n        /*\n          No need to keep the reference of DataHandler here\n          because we don't need to do the cleanup.\n          `Stream#end()` will remove all listeners for us.\n        */\n        new DataHandler_1.default(self, {\n            stringNumbers: self.options.stringNumbers,\n        });\n        const clientCommandPromises = [];\n        if (self.options.connectionName) {\n            debug(\"set the connection name [%s]\", self.options.connectionName);\n            clientCommandPromises.push(self.client(\"setname\", self.options.connectionName).catch(utils_1.noop));\n        }\n        if (!self.options.disableClientInfo) {\n            debug(\"set the client info\");\n            clientCommandPromises.push((0, utils_1.getPackageMeta)()\n                .then((packageMeta) => {\n                return self\n                    .client(\"SETINFO\", \"LIB-VER\", packageMeta.version)\n                    .catch(utils_1.noop);\n            })\n                .catch(utils_1.noop));\n            clientCommandPromises.push(self\n                .client(\"SETINFO\", \"LIB-NAME\", ((_a = self.options) === null || _a === void 0 ? void 0 : _a.clientInfoTag)\n                ? `ioredis(${self.options.clientInfoTag})`\n                : \"ioredis\")\n                .catch(utils_1.noop));\n        }\n        Promise.all(clientCommandPromises)\n            .catch(utils_1.noop)\n            .finally(() => {\n            if (!self.options.enableReadyCheck) {\n                exports.readyHandler(self)();\n            }\n            if (self.options.enableReadyCheck) {\n                self._readyCheck(function (err, info) {\n                    if (connectionEpoch !== self.connectionEpoch) {\n                        return;\n                    }\n                    if (err) {\n                        if (!flushed) {\n                            self.recoverFromFatalError(new Error(\"Ready check failed: \" + err.message), err);\n                        }\n                    }\n                    else {\n                        if (self.connector.check(info)) {\n                            exports.readyHandler(self)();\n                        }\n                        else {\n                            self.disconnect(true);\n                        }\n                    }\n                });\n            }\n        });\n    };\n}\nexports.connectHandler = connectHandler;\nfunction abortError(command) {\n    const err = new redis_errors_1.AbortError(\"Command aborted due to connection close\");\n    err.command = {\n        name: command.name,\n        args: command.args,\n    };\n    return err;\n}\n// If a contiguous set of pipeline commands starts from index zero then they\n// can be safely reattempted. If however we have a chain of pipelined commands\n// starting at index 1 or more it means we received a partial response before\n// the connection close and those pipelined commands must be aborted. For\n// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after\n// aborting and purging we'll have a queue that looks like this: [0, 1, 2]\nfunction abortIncompletePipelines(commandQueue) {\n    var _a;\n    let expectedIndex = 0;\n    for (let i = 0; i < commandQueue.length;) {\n        const command = (_a = commandQueue.peekAt(i)) === null || _a === void 0 ? void 0 : _a.command;\n        const pipelineIndex = command.pipelineIndex;\n        if (pipelineIndex === undefined || pipelineIndex === 0) {\n            expectedIndex = 0;\n        }\n        if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) {\n            commandQueue.remove(i, 1);\n            command.reject(abortError(command));\n            continue;\n        }\n        i++;\n    }\n}\n// If only a partial transaction result was received before connection close,\n// we have to abort any transaction fragments that may have ended up in the\n// offline queue\nfunction abortTransactionFragments(commandQueue) {\n    var _a;\n    for (let i = 0; i < commandQueue.length;) {\n        const command = (_a = commandQueue.peekAt(i)) === null || _a === void 0 ? void 0 : _a.command;\n        if (command.name === \"multi\") {\n            break;\n        }\n        if (command.name === \"exec\") {\n            commandQueue.remove(i, 1);\n            command.reject(abortError(command));\n            break;\n        }\n        if (command.inTransaction) {\n            commandQueue.remove(i, 1);\n            command.reject(abortError(command));\n        }\n        else {\n            i++;\n        }\n    }\n}\nfunction closeHandler(self) {\n    return function () {\n        const prevStatus = self.status;\n        self.setStatus(\"close\");\n        if (self.commandQueue.length) {\n            abortIncompletePipelines(self.commandQueue);\n        }\n        if (self.offlineQueue.length) {\n            abortTransactionFragments(self.offlineQueue);\n        }\n        if (prevStatus === \"ready\") {\n            if (!self.prevCondition) {\n                self.prevCondition = self.condition;\n            }\n            if (self.commandQueue.length) {\n                self.prevCommandQueue = self.commandQueue;\n            }\n        }\n        if (self.manuallyClosing) {\n            self.manuallyClosing = false;\n            debug(\"skip reconnecting since the connection is manually closed.\");\n            return close();\n        }\n        if (typeof self.options.retryStrategy !== \"function\") {\n            debug(\"skip reconnecting because `retryStrategy` is not a function\");\n            return close();\n        }\n        const retryDelay = self.options.retryStrategy(++self.retryAttempts);\n        if (typeof retryDelay !== \"number\") {\n            debug(\"skip reconnecting because `retryStrategy` doesn't return a number\");\n            return close();\n        }\n        debug(\"reconnect in %sms\", retryDelay);\n        self.setStatus(\"reconnecting\", retryDelay);\n        self.reconnectTimeout = setTimeout(function () {\n            self.reconnectTimeout = null;\n            self.connect().catch(utils_1.noop);\n        }, retryDelay);\n        const { maxRetriesPerRequest } = self.options;\n        if (typeof maxRetriesPerRequest === \"number\") {\n            if (maxRetriesPerRequest < 0) {\n                debug(\"maxRetriesPerRequest is negative, ignoring...\");\n            }\n            else {\n                const remainder = self.retryAttempts % (maxRetriesPerRequest + 1);\n                if (remainder === 0) {\n                    debug(\"reach maxRetriesPerRequest limitation, flushing command queue...\");\n                    self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest));\n                }\n            }\n        }\n    };\n    function close() {\n        self.setStatus(\"end\");\n        self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n    }\n}\nexports.closeHandler = closeHandler;\nfunction errorHandler(self) {\n    return function (error) {\n        debug(\"error: %s\", error);\n        self.silentEmit(\"error\", error);\n    };\n}\nexports.errorHandler = errorHandler;\nfunction readyHandler(self) {\n    return function () {\n        self.setStatus(\"ready\");\n        self.retryAttempts = 0;\n        if (self.options.monitor) {\n            self.call(\"monitor\").then(() => self.setStatus(\"monitoring\"), (error) => self.emit(\"error\", error));\n            const { sendCommand } = self;\n            self.sendCommand = function (command) {\n                if (Command_1.default.checkFlag(\"VALID_IN_MONITOR_MODE\", command.name)) {\n                    return sendCommand.call(self, command);\n                }\n                command.reject(new Error(\"Connection is in monitoring mode, can't process commands.\"));\n                return command.promise;\n            };\n            self.once(\"close\", function () {\n                delete self.sendCommand;\n            });\n            return;\n        }\n        const finalSelect = self.prevCondition\n            ? self.prevCondition.select\n            : self.condition.select;\n        if (self.options.readOnly) {\n            debug(\"set the connection to readonly mode\");\n            self.readonly().catch(utils_1.noop);\n        }\n        if (self.prevCondition) {\n            const condition = self.prevCondition;\n            self.prevCondition = null;\n            if (condition.subscriber && self.options.autoResubscribe) {\n                // We re-select the previous db first since\n                // `SELECT` command is not valid in sub mode.\n                if (self.condition.select !== finalSelect) {\n                    debug(\"connect to db [%d]\", finalSelect);\n                    self.select(finalSelect);\n                }\n                const subscribeChannels = condition.subscriber.channels(\"subscribe\");\n                if (subscribeChannels.length) {\n                    debug(\"subscribe %d channels\", subscribeChannels.length);\n                    self.subscribe(subscribeChannels);\n                }\n                const psubscribeChannels = condition.subscriber.channels(\"psubscribe\");\n                if (psubscribeChannels.length) {\n                    debug(\"psubscribe %d channels\", psubscribeChannels.length);\n                    self.psubscribe(psubscribeChannels);\n                }\n                const ssubscribeChannels = condition.subscriber.channels(\"ssubscribe\");\n                if (ssubscribeChannels.length) {\n                    debug(\"ssubscribe %s\", ssubscribeChannels.length);\n                    for (const channel of ssubscribeChannels) {\n                        self.ssubscribe(channel);\n                    }\n                }\n            }\n        }\n        if (self.prevCommandQueue) {\n            if (self.options.autoResendUnfulfilledCommands) {\n                debug(\"resend %d unfulfilled commands\", self.prevCommandQueue.length);\n                while (self.prevCommandQueue.length > 0) {\n                    const item = self.prevCommandQueue.shift();\n                    if (item.select !== self.condition.select &&\n                        item.command.name !== \"select\") {\n                        self.select(item.select);\n                    }\n                    self.sendCommand(item.command, item.stream);\n                }\n            }\n            else {\n                self.prevCommandQueue = null;\n            }\n        }\n        if (self.offlineQueue.length) {\n            debug(\"send %d commands in offline queue\", self.offlineQueue.length);\n            const offlineQueue = self.offlineQueue;\n            self.resetOfflineQueue();\n            while (offlineQueue.length > 0) {\n                const item = offlineQueue.shift();\n                if (item.select !== self.condition.select &&\n                    item.command.name !== \"select\") {\n                    self.select(item.select);\n                }\n                self.sendCommand(item.command, item.stream);\n            }\n        }\n        if (self.condition.select !== finalSelect) {\n            debug(\"connect to db [%d]\", finalSelect);\n            self.select(finalSelect);\n        }\n    };\n}\nexports.readyHandler = readyHandler;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_REDIS_OPTIONS = void 0;\nexports.DEFAULT_REDIS_OPTIONS = {\n    // Connection\n    port: 6379,\n    host: \"localhost\",\n    family: 0,\n    connectTimeout: 10000,\n    disconnectTimeout: 2000,\n    retryStrategy: function (times) {\n        return Math.min(times * 50, 2000);\n    },\n    keepAlive: 0,\n    noDelay: true,\n    connectionName: null,\n    disableClientInfo: false,\n    clientInfoTag: undefined,\n    // Sentinel\n    sentinels: null,\n    name: null,\n    role: \"master\",\n    sentinelRetryStrategy: function (times) {\n        return Math.min(times * 10, 1000);\n    },\n    sentinelReconnectStrategy: function () {\n        // This strategy only applies when sentinels are used for detecting\n        // a failover, not during initial master resolution.\n        // The deployment can still function when some of the sentinels are down\n        // for a long period of time, so we may not want to attempt reconnection\n        // very often. Therefore the default interval is fairly long (1 minute).\n        return 60000;\n    },\n    natMap: null,\n    enableTLSForSentinelMode: false,\n    updateSentinels: true,\n    failoverDetector: false,\n    // Status\n    username: null,\n    password: null,\n    db: 0,\n    // Others\n    enableOfflineQueue: true,\n    enableReadyCheck: true,\n    autoResubscribe: true,\n    autoResendUnfulfilledCommands: true,\n    lazyConnect: false,\n    keyPrefix: \"\",\n    reconnectOnError: null,\n    readOnly: false,\n    stringNumbers: false,\n    maxRetriesPerRequest: 20,\n    maxLoadingRetryTime: 10000,\n    enableAutoPipelining: false,\n    autoPipeliningIgnoredCommands: [],\n    sentinelMaxConnections: 10,\n    blockingTimeoutGrace: 100,\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst events_1 = require(\"events\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst cluster_1 = require(\"./cluster\");\nconst Command_1 = require(\"./Command\");\nconst connectors_1 = require(\"./connectors\");\nconst SentinelConnector_1 = require(\"./connectors/SentinelConnector\");\nconst eventHandler = require(\"./redis/event_handler\");\nconst RedisOptions_1 = require(\"./redis/RedisOptions\");\nconst ScanStream_1 = require(\"./ScanStream\");\nconst transaction_1 = require(\"./transaction\");\nconst utils_1 = require(\"./utils\");\nconst tracing_1 = require(\"./tracing\");\nconst applyMixin_1 = require(\"./utils/applyMixin\");\nconst Commander_1 = require(\"./utils/Commander\");\nconst lodash_1 = require(\"./utils/lodash\");\nconst Deque = require(\"denque\");\nconst debug = (0, utils_1.Debug)(\"redis\");\n/**\n * This is the major component of ioredis.\n * Use it to connect to a standalone Redis server or Sentinels.\n *\n * ```typescript\n * const redis = new Redis(); // Default port is 6379\n * async function main() {\n *   redis.set(\"foo\", \"bar\");\n *   redis.get(\"foo\", (err, result) => {\n *     // `result` should be \"bar\"\n *     console.log(err, result);\n *   });\n *   // Or use Promise\n *   const result = await redis.get(\"foo\");\n * }\n * ```\n */\nclass Redis extends Commander_1.default {\n    constructor(arg1, arg2, arg3) {\n        super();\n        this.status = \"wait\";\n        /**\n         * @ignore\n         */\n        this.isCluster = false;\n        this.reconnectTimeout = null;\n        this.connectionEpoch = 0;\n        this.retryAttempts = 0;\n        this.manuallyClosing = false;\n        // Prepare autopipelines structures\n        this._autoPipelines = new Map();\n        this._runningAutoPipelines = new Set();\n        this.parseOptions(arg1, arg2, arg3);\n        events_1.EventEmitter.call(this);\n        this.resetCommandQueue();\n        this.resetOfflineQueue();\n        if (this.options.Connector) {\n            this.connector = new this.options.Connector(this.options);\n        }\n        else if (this.options.sentinels) {\n            const sentinelConnector = new SentinelConnector_1.default(this.options);\n            sentinelConnector.emitter = this;\n            this.connector = sentinelConnector;\n        }\n        else {\n            this.connector = new connectors_1.StandaloneConnector(this.options);\n        }\n        if (this.options.scripts) {\n            Object.entries(this.options.scripts).forEach(([name, definition]) => {\n                this.defineCommand(name, definition);\n            });\n        }\n        // end(or wait) -> connecting -> connect -> ready -> end\n        if (this.options.lazyConnect) {\n            this.setStatus(\"wait\");\n        }\n        else {\n            this.connect().catch(lodash_1.noop);\n        }\n    }\n    /**\n     * Create a Redis instance.\n     * This is the same as `new Redis()` but is included for compatibility with node-redis.\n     */\n    static createClient(...args) {\n        return new Redis(...args);\n    }\n    get autoPipelineQueueSize() {\n        let queued = 0;\n        for (const pipeline of this._autoPipelines.values()) {\n            queued += pipeline.length;\n        }\n        return queued;\n    }\n    /**\n     * Create a connection to Redis.\n     * This method will be invoked automatically when creating a new Redis instance\n     * unless `lazyConnect: true` is passed.\n     *\n     * When calling this method manually, a Promise is returned, which will\n     * be resolved when the connection status is ready. The promise can reject\n     * if the connection fails, times out, or if Redis is already connecting/connected.\n     */\n    connect(callback) {\n        const promise = (0, tracing_1.traceConnect)(() => this._connect(), () => {\n            const { address, port } = this._getServerAddress();\n            return {\n                serverAddress: address,\n                serverPort: port,\n                connectionEpoch: this.connectionEpoch,\n            };\n        });\n        return (0, standard_as_callback_1.default)(promise, callback);\n    }\n    _connect() {\n        return new Promise((resolve, reject) => {\n            if (this.status === \"connecting\" ||\n                this.status === \"connect\" ||\n                this.status === \"ready\") {\n                reject(new Error(\"Redis is already connecting/connected\"));\n                return;\n            }\n            this.connectionEpoch += 1;\n            this.setStatus(\"connecting\");\n            const { options } = this;\n            this.condition = {\n                select: options.db,\n                auth: options.username\n                    ? [options.username, options.password]\n                    : options.password,\n                subscriber: false,\n            };\n            const _this = this;\n            (0, standard_as_callback_1.default)(this.connector.connect(function (type, err) {\n                _this.silentEmit(type, err);\n            }), function (err, stream) {\n                if (err) {\n                    _this.flushQueue(err);\n                    _this.silentEmit(\"error\", err);\n                    reject(err);\n                    _this.setStatus(\"end\");\n                    return;\n                }\n                let CONNECT_EVENT = options.tls ? \"secureConnect\" : \"connect\";\n                if (\"sentinels\" in options &&\n                    options.sentinels &&\n                    !options.enableTLSForSentinelMode) {\n                    CONNECT_EVENT = \"connect\";\n                }\n                _this.stream = stream;\n                if (options.noDelay) {\n                    stream.setNoDelay(true);\n                }\n                // Node ignores setKeepAlive before connect, therefore we wait for the event:\n                // https://github.com/nodejs/node/issues/31663\n                if (typeof options.keepAlive === \"number\") {\n                    if (stream.connecting) {\n                        stream.once(CONNECT_EVENT, () => {\n                            stream.setKeepAlive(true, options.keepAlive);\n                        });\n                    }\n                    else {\n                        stream.setKeepAlive(true, options.keepAlive);\n                    }\n                }\n                if (stream.connecting) {\n                    stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this));\n                    if (options.connectTimeout) {\n                        /*\n                         * Typically, Socket#setTimeout(0) will clear the timer\n                         * set before. However, in some platforms (Electron 3.x~4.x),\n                         * the timer will not be cleared. So we introduce a variable here.\n                         *\n                         * See https://github.com/electron/electron/issues/14915\n                         */\n                        let connectTimeoutCleared = false;\n                        stream.setTimeout(options.connectTimeout, function () {\n                            if (connectTimeoutCleared) {\n                                return;\n                            }\n                            stream.setTimeout(0);\n                            stream.destroy();\n                            const err = new Error(\"connect ETIMEDOUT\");\n                            // @ts-expect-error\n                            err.errorno = \"ETIMEDOUT\";\n                            // @ts-expect-error\n                            err.code = \"ETIMEDOUT\";\n                            // @ts-expect-error\n                            err.syscall = \"connect\";\n                            eventHandler.errorHandler(_this)(err);\n                        });\n                        stream.once(CONNECT_EVENT, function () {\n                            connectTimeoutCleared = true;\n                            stream.setTimeout(0);\n                        });\n                    }\n                }\n                else if (stream.destroyed) {\n                    const firstError = _this.connector.firstError;\n                    if (firstError) {\n                        process.nextTick(() => {\n                            eventHandler.errorHandler(_this)(firstError);\n                        });\n                    }\n                    process.nextTick(eventHandler.closeHandler(_this));\n                }\n                else {\n                    process.nextTick(eventHandler.connectHandler(_this));\n                }\n                if (!stream.destroyed) {\n                    stream.once(\"error\", eventHandler.errorHandler(_this));\n                    stream.once(\"close\", eventHandler.closeHandler(_this));\n                }\n                const connectionReadyHandler = function () {\n                    _this.removeListener(\"close\", connectionCloseHandler);\n                    resolve();\n                };\n                var connectionCloseHandler = function () {\n                    _this.removeListener(\"ready\", connectionReadyHandler);\n                    reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n                };\n                _this.once(\"ready\", connectionReadyHandler);\n                _this.once(\"close\", connectionCloseHandler);\n            });\n        });\n    }\n    /**\n     * Disconnect from Redis.\n     *\n     * This method closes the connection immediately,\n     * and may lose some pending replies that haven't written to client.\n     * If you want to wait for the pending replies, use Redis#quit instead.\n     */\n    disconnect(reconnect = false) {\n        if (!reconnect) {\n            this.manuallyClosing = true;\n        }\n        if (this.reconnectTimeout && !reconnect) {\n            clearTimeout(this.reconnectTimeout);\n            this.reconnectTimeout = null;\n        }\n        if (this.status === \"wait\") {\n            eventHandler.closeHandler(this)();\n        }\n        else {\n            this.connector.disconnect();\n        }\n    }\n    /**\n     * Disconnect from Redis.\n     *\n     * @deprecated\n     */\n    end() {\n        this.disconnect();\n    }\n    /**\n     * Create a new instance with the same options as the current one.\n     *\n     * @example\n     * ```js\n     * var redis = new Redis(6380);\n     * var anotherRedis = redis.duplicate();\n     * ```\n     */\n    duplicate(override) {\n        return new Redis({ ...this.options, ...override });\n    }\n    /**\n     * Mode of the connection.\n     *\n     * One of `\"normal\"`, `\"subscriber\"`, or `\"monitor\"`. When the connection is\n     * not in `\"normal\"` mode, certain commands are not allowed.\n     */\n    get mode() {\n        var _a;\n        return this.options.monitor\n            ? \"monitor\"\n            : ((_a = this.condition) === null || _a === void 0 ? void 0 : _a.subscriber)\n                ? \"subscriber\"\n                : \"normal\";\n    }\n    /**\n     * Listen for all requests received by the server in real time.\n     *\n     * This command will create a new connection to Redis and send a\n     * MONITOR command via the new connection in order to avoid disturbing\n     * the current connection.\n     *\n     * @param callback The callback function. If omit, a promise will be returned.\n     * @example\n     * ```js\n     * var redis = new Redis();\n     * redis.monitor(function (err, monitor) {\n     *   // Entering monitoring mode.\n     *   monitor.on('monitor', function (time, args, source, database) {\n     *     console.log(time + \": \" + util.inspect(args));\n     *   });\n     * });\n     *\n     * // supports promise as well as other commands\n     * redis.monitor().then(function (monitor) {\n     *   monitor.on('monitor', function (time, args, source, database) {\n     *     console.log(time + \": \" + util.inspect(args));\n     *   });\n     * });\n     * ```\n     */\n    monitor(callback) {\n        const monitorInstance = this.duplicate({\n            monitor: true,\n            lazyConnect: false,\n        });\n        return (0, standard_as_callback_1.default)(new Promise(function (resolve, reject) {\n            monitorInstance.once(\"error\", reject);\n            monitorInstance.once(\"monitoring\", function () {\n                resolve(monitorInstance);\n            });\n        }), callback);\n    }\n    /**\n     * Send a command to Redis\n     *\n     * This method is used internally and in most cases you should not\n     * use it directly. If you need to send a command that is not supported\n     * by the library, you can use the `call` method:\n     *\n     * ```js\n     * const redis = new Redis();\n     *\n     * redis.call('set', 'foo', 'bar');\n     * // or\n     * redis.call(['set', 'foo', 'bar']);\n     * ```\n     *\n     * @ignore\n     */\n    sendCommand(command, stream) {\n        var _a, _b;\n        if (this.status === \"wait\") {\n            this.connect().catch(lodash_1.noop);\n        }\n        if (this.status === \"end\") {\n            command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n            return command.promise;\n        }\n        if (((_a = this.condition) === null || _a === void 0 ? void 0 : _a.subscriber) &&\n            !Command_1.default.checkFlag(\"VALID_IN_SUBSCRIBER_MODE\", command.name)) {\n            command.reject(new Error(\"Connection in subscriber mode, only subscriber commands may be used\"));\n            return command.promise;\n        }\n        if (typeof this.options.commandTimeout === \"number\") {\n            command.setTimeout(this.options.commandTimeout);\n        }\n        const blockingTimeout = this.getBlockingTimeoutInMs(command);\n        let writable = this.status === \"ready\" ||\n            (!stream &&\n                this.status === \"connect\" &&\n                (0, commands_1.exists)(command.name, { caseInsensitive: true }) &&\n                ((0, commands_1.hasFlag)(command.name, \"loading\", { nameCaseInsensitive: true }) ||\n                    Command_1.default.checkFlag(\"HANDSHAKE_COMMANDS\", command.name)));\n        if (!this.stream) {\n            writable = false;\n        }\n        else if (!this.stream.writable) {\n            writable = false;\n            // @ts-expect-error\n        }\n        else if (this.stream._writableState && this.stream._writableState.ended) {\n            // TODO: We should be able to remove this as the PR has already been merged.\n            // https://github.com/iojs/io.js/pull/1217\n            writable = false;\n        }\n        if (!writable) {\n            if (!this.options.enableOfflineQueue) {\n                command.reject(new Error(\"Stream isn't writeable and enableOfflineQueue options is false\"));\n                return command.promise;\n            }\n            if (command.name === \"quit\" && this.offlineQueue.length === 0) {\n                this.disconnect();\n                command.resolve(Buffer.from(\"OK\"));\n                return command.promise;\n            }\n            // @ts-expect-error\n            if (debug.enabled) {\n                debug(\"queue command[%s]: %d -> %s(%o)\", this._getDescription(), this.condition.select, command.name, command.args);\n            }\n            this.offlineQueue.push({\n                command: command,\n                stream: stream,\n                select: this.condition.select,\n            });\n            // For blocking commands in the offline queue, arm a client-side timeout\n            // only when blockingTimeout is configured. Without this option, queued\n            // blocking commands may wait indefinitely on a dead connection.\n            if (Command_1.default.checkFlag(\"BLOCKING_COMMANDS\", command.name)) {\n                const offlineTimeout = this.getConfiguredBlockingTimeout();\n                if (offlineTimeout !== undefined) {\n                    command.setBlockingTimeout(offlineTimeout);\n                }\n            }\n        }\n        else {\n            // @ts-expect-error\n            if (debug.enabled) {\n                debug(\"write command[%s]: %d -> %s(%o)\", this._getDescription(), (_b = this.condition) === null || _b === void 0 ? void 0 : _b.select, command.name, command.args);\n            }\n            if (stream) {\n                if (\"isPipeline\" in stream && stream.isPipeline) {\n                    stream.write(command.toWritable(stream.destination.redis.stream));\n                }\n                else {\n                    stream.write(command.toWritable(stream));\n                }\n            }\n            else {\n                this.stream.write(command.toWritable(this.stream));\n            }\n            this.commandQueue.push({\n                command: command,\n                stream: stream,\n                select: this.condition.select,\n            });\n            if (blockingTimeout !== undefined) {\n                command.setBlockingTimeout(blockingTimeout);\n            }\n            if (Command_1.default.checkFlag(\"WILL_DISCONNECT\", command.name)) {\n                this.manuallyClosing = true;\n            }\n            if (this.options.socketTimeout !== undefined &&\n                this.socketTimeoutTimer === undefined) {\n                this.setSocketTimeout();\n            }\n        }\n        if (command.name === \"select\" && (0, utils_1.isInt)(command.args[0])) {\n            const db = parseInt(command.args[0], 10);\n            if (this.condition.select !== db) {\n                this.condition.select = db;\n                this.emit(\"select\", db);\n                debug(\"switch to db [%d]\", this.condition.select);\n            }\n        }\n        if (!writable || command.isTraced) {\n            return command.promise;\n        }\n        // Trace on the write path only, and only once per command. Commands may\n        // pass through sendCommand multiple times (offline queue flush,\n        // prevCommandQueue resend after reconnect). The isTraced flag ensures\n        // we don't emit duplicate trace events.\n        command.isTraced = true;\n        return (0, tracing_1.traceCommand)(() => command.promise, () => this._buildCommandContext(command));\n    }\n    getBlockingTimeoutInMs(command) {\n        var _a;\n        if (!Command_1.default.checkFlag(\"BLOCKING_COMMANDS\", command.name)) {\n            return undefined;\n        }\n        // Feature is opt-in: only enabled when blockingTimeout is set to a positive number\n        const configuredTimeout = this.getConfiguredBlockingTimeout();\n        if (configuredTimeout === undefined) {\n            return undefined;\n        }\n        const timeout = command.extractBlockingTimeout();\n        if (typeof timeout === \"number\") {\n            if (timeout > 0) {\n                // Finite timeout from command args - add grace period\n                return (timeout +\n                    ((_a = this.options.blockingTimeoutGrace) !== null && _a !== void 0 ? _a : RedisOptions_1.DEFAULT_REDIS_OPTIONS.blockingTimeoutGrace));\n            }\n            // Command has timeout=0 (block forever), use blockingTimeout option as safety net\n            return configuredTimeout;\n        }\n        if (timeout === null) {\n            // No BLOCK option found (e.g., XREAD without BLOCK), use blockingTimeout as safety net\n            return configuredTimeout;\n        }\n        return undefined;\n    }\n    getConfiguredBlockingTimeout() {\n        if (typeof this.options.blockingTimeout === \"number\" &&\n            this.options.blockingTimeout > 0) {\n            return this.options.blockingTimeout;\n        }\n        return undefined;\n    }\n    setSocketTimeout() {\n        this.socketTimeoutTimer = setTimeout(() => {\n            this.stream.destroy(new Error(`Socket timeout. Expecting data, but didn't receive any in ${this.options.socketTimeout}ms.`));\n            this.socketTimeoutTimer = undefined;\n        }, this.options.socketTimeout);\n        // this handler must run after the \"data\" handler in \"DataHandler\"\n        // so that `this.commandQueue.length` will be updated\n        this.stream.once(\"data\", () => {\n            clearTimeout(this.socketTimeoutTimer);\n            this.socketTimeoutTimer = undefined;\n            if (this.commandQueue.length === 0)\n                return;\n            this.setSocketTimeout();\n        });\n    }\n    scanStream(options) {\n        return this.createScanStream(\"scan\", { options });\n    }\n    scanBufferStream(options) {\n        return this.createScanStream(\"scanBuffer\", { options });\n    }\n    sscanStream(key, options) {\n        return this.createScanStream(\"sscan\", { key, options });\n    }\n    sscanBufferStream(key, options) {\n        return this.createScanStream(\"sscanBuffer\", { key, options });\n    }\n    hscanStream(key, options) {\n        return this.createScanStream(\"hscan\", { key, options });\n    }\n    hscanBufferStream(key, options) {\n        return this.createScanStream(\"hscanBuffer\", { key, options });\n    }\n    zscanStream(key, options) {\n        return this.createScanStream(\"zscan\", { key, options });\n    }\n    zscanBufferStream(key, options) {\n        return this.createScanStream(\"zscanBuffer\", { key, options });\n    }\n    /**\n     * Emit only when there's at least one listener.\n     *\n     * @ignore\n     */\n    silentEmit(eventName, arg) {\n        let error;\n        if (eventName === \"error\") {\n            error = arg;\n            if (this.status === \"end\") {\n                return;\n            }\n            if (this.manuallyClosing) {\n                // ignore connection related errors when manually disconnecting\n                if (error instanceof Error &&\n                    (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG ||\n                        // @ts-expect-error\n                        error.syscall === \"connect\" ||\n                        // @ts-expect-error\n                        error.syscall === \"read\")) {\n                    return;\n                }\n            }\n        }\n        if (this.listeners(eventName).length > 0) {\n            return this.emit.apply(this, arguments);\n        }\n        if (error && error instanceof Error) {\n            console.error(\"[ioredis] Unhandled error event:\", error.stack);\n        }\n        return false;\n    }\n    /**\n     * @ignore\n     */\n    recoverFromFatalError(_commandError, err, options) {\n        this.flushQueue(err, options);\n        this.silentEmit(\"error\", err);\n        this.disconnect(true);\n    }\n    /**\n     * @ignore\n     */\n    handleReconnection(err, item) {\n        var _a;\n        let needReconnect = false;\n        if (this.options.reconnectOnError &&\n            !Command_1.default.checkFlag(\"IGNORE_RECONNECT_ON_ERROR\", item.command.name)) {\n            needReconnect = this.options.reconnectOnError(err);\n        }\n        switch (needReconnect) {\n            case 1:\n            case true:\n                if (this.status !== \"reconnecting\") {\n                    this.disconnect(true);\n                }\n                item.command.reject(err);\n                break;\n            case 2:\n                if (this.status !== \"reconnecting\") {\n                    this.disconnect(true);\n                }\n                if (((_a = this.condition) === null || _a === void 0 ? void 0 : _a.select) !== item.select &&\n                    item.command.name !== \"select\") {\n                    this.select(item.select);\n                }\n                // TODO\n                // @ts-expect-error\n                this.sendCommand(item.command);\n                break;\n            default:\n                item.command.reject(err);\n        }\n    }\n    /**\n     * @ignore\n     */\n    _getServerAddress() {\n        if (\"path\" in this.options && this.options.path) {\n            return { address: this.options.path, port: undefined };\n        }\n        return {\n            address: (\"host\" in this.options && this.options.host) || \"localhost\",\n            port: (\"port\" in this.options && this.options.port) || 6379,\n        };\n    }\n    _buildCommandContext(command) {\n        var _a, _b, _c;\n        const { address, port } = this._getServerAddress();\n        return {\n            command: command.name,\n            args: (0, tracing_1.sanitizeArgs)(command.name, command.args),\n            database: (_c = (_b = (_a = this.condition) === null || _a === void 0 ? void 0 : _a.select) !== null && _b !== void 0 ? _b : this.options.db) !== null && _c !== void 0 ? _c : 0,\n            serverAddress: address,\n            serverPort: port,\n        };\n    }\n    _buildBatchContext(batchSize) {\n        var _a, _b, _c;\n        const { address, port } = this._getServerAddress();\n        return {\n            batchMode: \"MULTI\",\n            batchSize,\n            database: (_c = (_b = (_a = this.condition) === null || _a === void 0 ? void 0 : _a.select) !== null && _b !== void 0 ? _b : this.options.db) !== null && _c !== void 0 ? _c : 0,\n            serverAddress: address,\n            serverPort: port,\n        };\n    }\n    /**\n     * Get description of the connection. Used for debugging.\n     */\n    _getDescription() {\n        let description;\n        if (\"path\" in this.options && this.options.path) {\n            description = this.options.path;\n        }\n        else if (this.stream &&\n            this.stream.remoteAddress &&\n            this.stream.remotePort) {\n            description = this.stream.remoteAddress + \":\" + this.stream.remotePort;\n        }\n        else if (\"host\" in this.options && this.options.host) {\n            description = this.options.host + \":\" + this.options.port;\n        }\n        else {\n            // Unexpected\n            description = \"\";\n        }\n        if (this.options.connectionName) {\n            description += ` (${this.options.connectionName})`;\n        }\n        return description;\n    }\n    resetCommandQueue() {\n        this.commandQueue = new Deque();\n    }\n    resetOfflineQueue() {\n        this.offlineQueue = new Deque();\n    }\n    parseOptions(...args) {\n        const options = {};\n        let isTls = false;\n        for (let i = 0; i < args.length; ++i) {\n            const arg = args[i];\n            if (arg === null || typeof arg === \"undefined\") {\n                continue;\n            }\n            if (typeof arg === \"object\") {\n                (0, lodash_1.defaults)(options, arg);\n            }\n            else if (typeof arg === \"string\") {\n                (0, lodash_1.defaults)(options, (0, utils_1.parseURL)(arg));\n                if (arg.startsWith(\"rediss://\")) {\n                    isTls = true;\n                }\n            }\n            else if (typeof arg === \"number\") {\n                options.port = arg;\n            }\n            else {\n                throw new Error(\"Invalid argument \" + arg);\n            }\n        }\n        if (isTls) {\n            (0, lodash_1.defaults)(options, { tls: true });\n        }\n        (0, lodash_1.defaults)(options, Redis.defaultOptions);\n        if (typeof options.port === \"string\") {\n            options.port = parseInt(options.port, 10);\n        }\n        if (typeof options.db === \"string\") {\n            options.db = parseInt(options.db, 10);\n        }\n        // @ts-expect-error\n        this.options = (0, utils_1.resolveTLSProfile)(options);\n    }\n    /**\n     * Change instance's status\n     */\n    setStatus(status, arg) {\n        // @ts-expect-error\n        if (debug.enabled) {\n            debug(\"status[%s]: %s -> %s\", this._getDescription(), this.status || \"[empty]\", status);\n        }\n        this.status = status;\n        process.nextTick(this.emit.bind(this, status, arg));\n    }\n    createScanStream(command, { key, options = {} }) {\n        return new ScanStream_1.default({\n            objectMode: true,\n            key: key,\n            redis: this,\n            command: command,\n            ...options,\n        });\n    }\n    /**\n     * Flush offline queue and command queue with error.\n     *\n     * @param error The error object to send to the commands\n     * @param options options\n     */\n    flushQueue(error, options) {\n        options = (0, lodash_1.defaults)({}, options, {\n            offlineQueue: true,\n            commandQueue: true,\n        });\n        let item;\n        if (options.offlineQueue) {\n            while ((item = this.offlineQueue.shift())) {\n                item.command.reject(error);\n            }\n        }\n        if (options.commandQueue) {\n            if (this.commandQueue.length > 0) {\n                if (this.stream) {\n                    this.stream.removeAllListeners(\"data\");\n                }\n                while ((item = this.commandQueue.shift())) {\n                    item.command.reject(error);\n                }\n            }\n        }\n    }\n    /**\n     * Check whether Redis has finished loading the persistent data and is able to\n     * process commands.\n     */\n    _readyCheck(callback) {\n        const _this = this;\n        this.info(function (err, res) {\n            if (err) {\n                if (err.message && err.message.includes(\"NOPERM\")) {\n                    console.warn(`Skipping the ready check because INFO command fails: \"${err.message}\". You can disable ready check with \"enableReadyCheck\". More: https://github.com/luin/ioredis/wiki/Disable-ready-check.`);\n                    return callback(null, {});\n                }\n                return callback(err);\n            }\n            if (typeof res !== \"string\") {\n                return callback(null, res);\n            }\n            const info = {};\n            const lines = res.split(\"\\r\\n\");\n            for (let i = 0; i < lines.length; ++i) {\n                const [fieldName, ...fieldValueParts] = lines[i].split(\":\");\n                const fieldValue = fieldValueParts.join(\":\");\n                if (fieldValue) {\n                    info[fieldName] = fieldValue;\n                }\n            }\n            if (!info.loading || info.loading === \"0\") {\n                callback(null, info);\n            }\n            else {\n                const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000;\n                const retryTime = _this.options.maxLoadingRetryTime &&\n                    _this.options.maxLoadingRetryTime < loadingEtaMs\n                    ? _this.options.maxLoadingRetryTime\n                    : loadingEtaMs;\n                debug(\"Redis server still loading, trying again in \" + retryTime + \"ms\");\n                setTimeout(function () {\n                    _this._readyCheck(callback);\n                }, retryTime);\n            }\n        }).catch(lodash_1.noop);\n    }\n}\nRedis.Cluster = cluster_1.default;\nRedis.Command = Command_1.default;\n/**\n * Default options\n */\nRedis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS;\n(0, applyMixin_1.default)(Redis, events_1.EventEmitter);\n(0, transaction_1.addTransactionSupport)(Redis.prototype);\nexports.default = Redis;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.print = exports.ReplyError = exports.SentinelIterator = exports.SentinelConnector = exports.AbstractConnector = exports.Pipeline = exports.ScanStream = exports.Command = exports.Cluster = exports.Redis = exports.default = void 0;\nexports = module.exports = require(\"./Redis\").default;\nvar Redis_1 = require(\"./Redis\");\nObject.defineProperty(exports, \"default\", { enumerable: true, get: function () { return Redis_1.default; } });\nvar Redis_2 = require(\"./Redis\");\nObject.defineProperty(exports, \"Redis\", { enumerable: true, get: function () { return Redis_2.default; } });\nvar cluster_1 = require(\"./cluster\");\nObject.defineProperty(exports, \"Cluster\", { enumerable: true, get: function () { return cluster_1.default; } });\n/**\n * @ignore\n */\nvar Command_1 = require(\"./Command\");\nObject.defineProperty(exports, \"Command\", { enumerable: true, get: function () { return Command_1.default; } });\n/**\n * @ignore\n */\nvar ScanStream_1 = require(\"./ScanStream\");\nObject.defineProperty(exports, \"ScanStream\", { enumerable: true, get: function () { return ScanStream_1.default; } });\n/**\n * @ignore\n */\nvar Pipeline_1 = require(\"./Pipeline\");\nObject.defineProperty(exports, \"Pipeline\", { enumerable: true, get: function () { return Pipeline_1.default; } });\n/**\n * @ignore\n */\nvar AbstractConnector_1 = require(\"./connectors/AbstractConnector\");\nObject.defineProperty(exports, \"AbstractConnector\", { enumerable: true, get: function () { return AbstractConnector_1.default; } });\n/**\n * @ignore\n */\nvar SentinelConnector_1 = require(\"./connectors/SentinelConnector\");\nObject.defineProperty(exports, \"SentinelConnector\", { enumerable: true, get: function () { return SentinelConnector_1.default; } });\nObject.defineProperty(exports, \"SentinelIterator\", { enumerable: true, get: function () { return SentinelConnector_1.SentinelIterator; } });\n// No TS typings\nexports.ReplyError = require(\"redis-errors\").ReplyError;\n/**\n * @ignore\n */\nObject.defineProperty(exports, \"Promise\", {\n    get() {\n        console.warn(\"ioredis v5 does not support plugging third-party Promise library anymore. Native Promise will be used.\");\n        return Promise;\n    },\n    set(_lib) {\n        console.warn(\"ioredis v5 does not support plugging third-party Promise library anymore. Native Promise will be used.\");\n    },\n});\n/**\n * @ignore\n */\nfunction print(err, reply) {\n    if (err) {\n        console.log(\"Error: \" + err);\n    }\n    else {\n        console.log(\"Reply: \" + reply);\n    }\n}\nexports.print = print;\n","import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { tmpdir } from \"node:os\";\nimport { ROUTE_MANIFEST_REL_PATH, parseStoredRouteManifest } from \"@keystrokehq/shared\";\n//#region src/pack-dir.ts\n/**\n* Pack a directory tree that contains a `dist/` folder into a gzip tarball\n* suitable for project-server extraction.\n*/\nfunction packDistTree(rootContainingDist) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-pack-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-czf\",\n\t\t\tarchivePath,\n\t\t\t\"--exclude=._*\",\n\t\t\t\"--exclude=.DS_Store\",\n\t\t\t\"-C\",\n\t\t\trootContainingDist,\n\t\t\t\"dist\"\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to pack project artifact\");\n\t\treturn readFileSync(archivePath);\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/extract-artifact.ts\n/** Extract a packed project artifact tarball into `destDir` (creates `destDir/dist/`). */\nfunction extractProjectArtifact(archive, destDir) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-extract-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\twriteFileSync(archivePath, archive);\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-xzf\",\n\t\t\tarchivePath,\n\t\t\t\"-C\",\n\t\t\tdestDir\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to extract project artifact\");\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/merge-route-manifest.ts\nfunction moduleFileOf(entry) {\n\treturn \"moduleFile\" in entry && typeof entry.moduleFile === \"string\" ? entry.moduleFile : void 0;\n}\n/** Replace manifest rows for rebuilt modules while keeping untouched routes and metadata. */\nfunction mergeStoredRouteManifest(base, rebuiltEntries) {\n\tconst rebuiltModuleFiles = new Set(rebuiltEntries.map(moduleFileOf).filter((value) => Boolean(value)));\n\tconst keptEntries = base.entries.filter((entry) => {\n\t\tconst moduleFile = moduleFileOf(entry);\n\t\tif (!moduleFile) return true;\n\t\treturn !rebuiltModuleFiles.has(moduleFile);\n\t});\n\tconst filteredRebuilt = rebuiltEntries.filter((entry) => entry.kind !== \"health\");\n\treturn {\n\t\t...base,\n\t\tentries: [...keptEntries, ...filteredRebuilt]\n\t};\n}\n//#endregion\n//#region src/merge-filtered-artifact.ts\nasync function mergeFilteredArtifact(input) {\n\tconst mergeRoot = mkdtempSync(join(tmpdir(), \"keystroke-artifact-merge-\"));\n\ttry {\n\t\textractProjectArtifact(input.baseArchive, mergeRoot);\n\t\tconst manifestPath = join(mergeRoot, ROUTE_MANIFEST_REL_PATH);\n\t\tconst mergedManifest = mergeStoredRouteManifest(parseStoredRouteManifest(JSON.parse(readFileSync(manifestPath, \"utf8\"))), input.filtered.manifestEntries);\n\t\twriteFileSync(manifestPath, `${JSON.stringify(mergedManifest, null, 2)}\\n`);\n\t\tfor (const file of input.filtered.files) {\n\t\t\tconst destination = join(mergeRoot, \"dist\", file.relativePath);\n\t\t\tmkdirSync(dirname(destination), { recursive: true });\n\t\t\twriteFileSync(destination, file.contents);\n\t\t\tif (file.sourceMap) writeFileSync(`${destination}.map`, file.sourceMap);\n\t\t}\n\t\treturn packDistTree(mergeRoot);\n\t} finally {\n\t\trmSync(mergeRoot, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/pack-artifact.ts\n/** Pack `dist/` into a gzip tarball suitable for `/app` extraction in the project server image. */\nfunction packProjectArtifact(projectRoot) {\n\tif (!existsSync(join(projectRoot, \"dist\"))) throw new Error(\"dist/ not found — run keystroke build first\");\n\treturn packDistTree(projectRoot);\n}\n//#endregion\nexport { packDistTree as a, extractProjectArtifact as i, mergeFilteredArtifact as n, mergeStoredRouteManifest as r, packProjectArtifact as t };\n\n//# sourceMappingURL=pack-artifact-DVnIKrsg.mjs.map","import { S as setDatabaseHandle, _ as users, a as mcpOauthConsent, b as getDbFromContext, c as authVerificationsSqlite, d as authJwks, f as authJwksSqlite, g as authAccountsSqlite, h as authAccounts, i as mcpOauthClientSqlite, l as authSessions, m as authDeviceCodesSqlite, n as mcpOauthAccessTokenSqlite, o as mcpOauthConsentSqlite, p as authDeviceCodes, r as mcpOauthClient, s as authVerifications, t as mcpOauthAccessToken, u as authSessionsSqlite, v as usersSqlite, x as isDatabaseInitialized, y as getDatabaseHandle } from \"./mcp-oauth-SRTcHMWZ.mjs\";\nimport { createRequire } from \"node:module\";\nimport { DEFAULT_PROJECT_ID, adaptPgMigrationsForSearchPath, assertPgIdent, buildPostgresUrl, createConnection as createConnection$1, createPublicScopedPool, decryptCredentialPayload, decryptCredentialPayload as decryptCredentialPayload$1, encryptCredentialPayload, encryptCredentialPayload as encryptCredentialPayload$1, inferDialect, loadMigrations, migratePgDatabase, qualifyConnectionUser, quotePgIdent, resolveMigrationsFolder as resolveMigrationsFolder$1, resolveMigrationsSchema, resolvePostgresConfigFromEnv, resolvePostgresUrlFromEnv, resolveSearchPath, resolveSqlitePath, runMigrations as runMigrations$1, runWithProjectScope, runWithTenantScope } from \"@keystrokehq/database\";\nimport { boolean, index, integer, jsonb, pgEnum, pgTable, primaryKey, text, timestamp, uniqueIndex } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, primaryKey as primaryKey$1, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from \"drizzle-orm/sqlite-core\";\nimport { and, and as and$1, asc, desc, eq, eq as eq$1, gt, inArray, inArray as inArray$1, isNull, isNull as isNull$1, max, ne, or, sql, sql as sql$1 } from \"drizzle-orm\";\nimport { existsSync, mkdirSync, unlinkSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport BetterSqlite3 from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { fileURLToPath } from \"node:url\";\nimport { migrate } from \"drizzle-orm/better-sqlite3/migrator\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { Redis } from \"ioredis\";\nimport { AppSlugSchema, ClaimableOrganizationSlugSchema, ORGANIZATION_SLUG_TAKEN_MESSAGE, OrganizationSlugSchema, PROJECT_SLUG_TAKEN_MESSAGE, ProjectSlugSchema, RESERVED_ORGANIZATION_SLUGS, normalizeOrganizationSidebarBranding, qualifyOrgSlug, slugifyAppName, slugifyOrganizationName, slugifyProjectName } from \"@keystrokehq/shared\";\nimport { containerPresignEndpointFromEnv, createContainerPresignStorage, createStorage, orgAgentBucketName } from \"@keystrokehq/storage\";\n//#region src/client/close.ts\nasync function closeDatabase() {\n\tif (!isDatabaseInitialized()) return;\n\tawait getDatabaseHandle().close();\n\tsetDatabaseHandle(void 0);\n}\n//#endregion\n//#region src/config/constants.ts\nconst DEFAULT_PLATFORM_DATABASE_URL = \"file:./data/public.db\";\n//#endregion\n//#region src/config/database-url.ts\nfunction resolvePlatformPostgresConfig(env = process.env) {\n\treturn resolvePostgresConfigFromEnv(env);\n}\nfunction resolvePlatformDatabaseUrl(env = process.env) {\n\tconst direct = env.DATABASE_URL?.trim();\n\tif (direct) {\n\t\tif (inferDialect(direct) === \"sqlite\") return direct;\n\t\treturn resolvePostgresUrlFromEnv(env);\n\t}\n\ttry {\n\t\treturn resolvePostgresUrlFromEnv(env);\n\t} catch {\n\t\treturn DEFAULT_PLATFORM_DATABASE_URL;\n\t}\n}\n//#endregion\n//#region src/connection/pg/driver.ts\nconst require = createRequire(import.meta.url);\n/**\n* Lazily load the native `pg` driver. Keeping it off the static import graph means\n* consumers that only reference platform-database helpers/types never force `pg`\n* into their bundle — it resolves from the runtime image only when a connection is\n* actually opened.\n*/\nfunction loadPg() {\n\treturn require(\"pg\");\n}\n/** Lazily load drizzle's node-postgres adapter — it statically imports `pg`. */\nfunction loadDrizzlePg() {\n\treturn require(\"drizzle-orm/node-postgres\");\n}\n//#endregion\n//#region src/schema/bundle.ts\nfunction buildPgSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { pg }]) => [name, pg]));\n}\nfunction buildSqliteSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { sqlite }]) => [name, sqlite]));\n}\n//#endregion\n//#region src/schema/tables/api-keys.ts\n/** Better Auth API Key shape (`apikey` model → physical `api_keys`). */\nconst authApiKeys = pgTable(\"api_keys\", {\n\tid: text(\"id\").primaryKey(),\n\tconfigId: text(\"config_id\").notNull().default(\"default\"),\n\tname: text(\"name\"),\n\tstart: text(\"start\"),\n\tprefix: text(\"prefix\"),\n\t/** Hashed secret for verification (Better Auth `key`). */\n\tkey: text(\"key\").notNull(),\n\t/** Encrypted plaintext secret — keystroke extension for re-display. */\n\tkeyCiphertext: text(\"key_ciphertext\"),\n\treferenceId: text(\"reference_id\").notNull(),\n\trefillInterval: integer(\"refill_interval\"),\n\trefillAmount: integer(\"refill_amount\"),\n\tlastRefillAt: timestamp(\"last_refill_at\", { withTimezone: true }),\n\tenabled: boolean(\"enabled\").default(true),\n\trateLimitEnabled: boolean(\"rate_limit_enabled\").default(true),\n\trateLimitTimeWindow: integer(\"rate_limit_time_window\"),\n\trateLimitMax: integer(\"rate_limit_max\"),\n\trequestCount: integer(\"request_count\").default(0),\n\tremaining: integer(\"remaining\"),\n\tlastRequest: timestamp(\"last_request\", { withTimezone: true }),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tpermissions: text(\"permissions\"),\n\tmetadata: text(\"metadata\")\n}, (table) => [\n\tindex(\"api_keys_reference_id_idx\").on(table.referenceId),\n\tindex(\"api_keys_config_id_idx\").on(table.configId),\n\tindex(\"api_keys_key_idx\").on(table.key)\n]);\nconst authApiKeysSqlite = sqliteTable(\"api_keys\", {\n\tid: text$1(\"id\").primaryKey(),\n\tconfigId: text$1(\"config_id\").notNull().default(\"default\"),\n\tname: text$1(\"name\"),\n\tstart: text$1(\"start\"),\n\tprefix: text$1(\"prefix\"),\n\tkey: text$1(\"key\").notNull(),\n\tkeyCiphertext: text$1(\"key_ciphertext\"),\n\treferenceId: text$1(\"reference_id\").notNull(),\n\trefillInterval: integer$1(\"refill_interval\"),\n\trefillAmount: integer$1(\"refill_amount\"),\n\tlastRefillAt: integer$1(\"last_refill_at\", { mode: \"timestamp_ms\" }),\n\tenabled: integer$1(\"enabled\", { mode: \"boolean\" }).default(true),\n\trateLimitEnabled: integer$1(\"rate_limit_enabled\", { mode: \"boolean\" }).default(true),\n\trateLimitTimeWindow: integer$1(\"rate_limit_time_window\"),\n\trateLimitMax: integer$1(\"rate_limit_max\"),\n\trequestCount: integer$1(\"request_count\").default(0),\n\tremaining: integer$1(\"remaining\"),\n\tlastRequest: integer$1(\"last_request\", { mode: \"timestamp_ms\" }),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tpermissions: text$1(\"permissions\"),\n\tmetadata: text$1(\"metadata\")\n}, (table) => [\n\tindex$1(\"api_keys_reference_id_idx\").on(table.referenceId),\n\tindex$1(\"api_keys_config_id_idx\").on(table.configId),\n\tindex$1(\"api_keys_key_idx\").on(table.key)\n]);\n//#endregion\n//#region src/schema/tables/organizations.ts\nconst organizations = pgTable(\"organizations\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tdbSchema: text(\"db_schema\").notNull(),\n\tdbUser: text(\"db_user\").notNull(),\n\tdbPasswordCiphertext: text(\"db_password_ciphertext\").notNull(),\n\tredisUrlCiphertext: text(\"redis_url_ciphertext\"),\n\thostingAppName: text(\"hosting_app_name\"),\n\truntimeId: text(\"runtime_id\"),\n\tbaseUrl: text(\"base_url\"),\n\tstorageBucket: text(\"storage_bucket\"),\n\tstorageEndpoint: text(\"storage_endpoint\"),\n\tstorageAccessKeyIdCiphertext: text(\"storage_access_key_id_ciphertext\"),\n\tstorageSecretAccessKeyCiphertext: text(\"storage_secret_access_key_ciphertext\"),\n\tstorageRegion: text(\"storage_region\"),\n\tstorageForcePathStyle: boolean(\"storage_force_path_style\"),\n\tcustomLogoEnabled: boolean(\"custom_logo_enabled\").notNull().default(false),\n\tcustomLogoExplicitlyDisabled: boolean(\"custom_logo_explicitly_disabled\").notNull().default(false),\n\tlogoLightUrl: text(\"logo_light_url\"),\n\tlogoDarkUrl: text(\"logo_dark_url\"),\n\tlogoHeightPx: integer(\"logo_height_px\").notNull().default(20),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tverifiedAt: timestamp(\"verified_at\", { withTimezone: true }),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"organizations_slug_unique\").on(table.slug)]);\nconst organizationsSqlite = sqliteTable(\"organizations\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tdbSchema: text$1(\"db_schema\").notNull(),\n\tdbUser: text$1(\"db_user\").notNull(),\n\tdbPasswordCiphertext: text$1(\"db_password_ciphertext\").notNull(),\n\tredisUrlCiphertext: text$1(\"redis_url_ciphertext\"),\n\thostingAppName: text$1(\"hosting_app_name\"),\n\truntimeId: text$1(\"runtime_id\"),\n\tbaseUrl: text$1(\"base_url\"),\n\tstorageBucket: text$1(\"storage_bucket\"),\n\tstorageEndpoint: text$1(\"storage_endpoint\"),\n\tstorageAccessKeyIdCiphertext: text$1(\"storage_access_key_id_ciphertext\"),\n\tstorageSecretAccessKeyCiphertext: text$1(\"storage_secret_access_key_ciphertext\"),\n\tstorageRegion: text$1(\"storage_region\"),\n\tstorageForcePathStyle: integer$1(\"storage_force_path_style\", { mode: \"boolean\" }),\n\tcustomLogoEnabled: integer$1(\"custom_logo_enabled\", { mode: \"boolean\" }).notNull().default(false),\n\tcustomLogoExplicitlyDisabled: integer$1(\"custom_logo_explicitly_disabled\", { mode: \"boolean\" }).notNull().default(false),\n\tlogoLightUrl: text$1(\"logo_light_url\"),\n\tlogoDarkUrl: text$1(\"logo_dark_url\"),\n\tlogoHeightPx: integer$1(\"logo_height_px\").notNull().default(20),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tverifiedAt: integer$1(\"verified_at\", { mode: \"timestamp_ms\" }),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"organizations_slug_unique\").on(table.slug)]);\n//#endregion\n//#region src/schema/tables/apps.ts\nconst apps = pgTable(\"apps\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").references(() => organizations.id, { onDelete: \"cascade\" }),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\").notNull(),\n\tdescription: text(\"description\").notNull(),\n\tcategory: text(\"category\").notNull(),\n\tlogo: text(\"logo\"),\n\tauthKind: text(\"auth_kind\").$type().notNull(),\n\toauthScopes: jsonb(\"oauth_scopes\").$type().notNull(),\n\tcredentialFields: jsonb(\"credential_fields\").$type().notNull().default({}),\n\tcredentialScheme: text(\"credential_scheme\").$type(),\n\turl: text(\"url\"),\n\tsource: text(\"source\").$type().notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"apps_slug_idx\").on(table.slug), index(\"apps_organization_id_idx\").on(table.organizationId)]);\nconst appsSqlite = sqliteTable(\"apps\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tdescription: text$1(\"description\").notNull(),\n\tcategory: text$1(\"category\").notNull(),\n\tlogo: text$1(\"logo\"),\n\tauthKind: text$1(\"auth_kind\").$type().notNull(),\n\toauthScopes: text$1(\"oauth_scopes\", { mode: \"json\" }).$type().notNull(),\n\tcredentialFields: text$1(\"credential_fields\", { mode: \"json\" }).$type().notNull().default({}),\n\tcredentialScheme: text$1(\"credential_scheme\").$type(),\n\turl: text$1(\"url\"),\n\tsource: text$1(\"source\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"apps_slug_idx\").on(table.slug), index$1(\"apps_organization_id_idx\").on(table.organizationId)]);\n//#endregion\n//#region src/schema/tables/oauth-apps.ts\nconst oauthApps = pgTable(\"oauth_apps\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprovider: text(\"provider\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\ttokenStrategy: text(\"token_strategy\").$type().notNull(),\n\tclientIdCiphertext: text(\"client_id_ciphertext\").notNull(),\n\tclientSecretCiphertext: text(\"client_secret_ciphertext\").notNull(),\n\tsigningSecretCiphertext: text(\"signing_secret_ciphertext\"),\n\tredirectUri: text(\"redirect_uri\"),\n\tmetadata: jsonb(\"metadata\").$type(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"oauth_apps_organization_id_slug_idx\").on(table.organizationId, table.slug), index(\"oauth_apps_slug_idx\").on(table.slug)]);\nconst oauthAppsSqlite = sqliteTable(\"oauth_apps\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tprovider: text$1(\"provider\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\ttokenStrategy: text$1(\"token_strategy\").$type().notNull(),\n\tclientIdCiphertext: text$1(\"client_id_ciphertext\").notNull(),\n\tclientSecretCiphertext: text$1(\"client_secret_ciphertext\").notNull(),\n\tsigningSecretCiphertext: text$1(\"signing_secret_ciphertext\"),\n\tredirectUri: text$1(\"redirect_uri\"),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"oauth_apps_organization_id_slug_idx\").on(table.organizationId, table.slug), index$1(\"oauth_apps_slug_idx\").on(table.slug)]);\n//#endregion\n//#region src/schema/tables/oauth-connections.ts\nconst oauthConnections = pgTable(\"oauth_connections\", {\n\tid: text(\"id\").primaryKey(),\n\tappId: text(\"app_id\").notNull().references(() => oauthApps.id, { onDelete: \"cascade\" }),\n\texternalId: text(\"external_id\").notNull(),\n\taccessTokenCiphertext: text(\"access_token_ciphertext\").notNull(),\n\trefreshTokenCiphertext: text(\"refresh_token_ciphertext\"),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\tgrantedScopes: jsonb(\"granted_scopes\").$type(),\n\tmetadata: jsonb(\"metadata\").$type(),\n\tconnectedAt: timestamp(\"connected_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"oauth_connections_app_external_unique\").on(table.appId, table.externalId), index(\"oauth_connections_external_id_idx\").on(table.externalId)]);\nconst oauthConnectionsSqlite = sqliteTable(\"oauth_connections\", {\n\tid: text$1(\"id\").primaryKey(),\n\tappId: text$1(\"app_id\").notNull().references(() => oauthAppsSqlite.id, { onDelete: \"cascade\" }),\n\texternalId: text$1(\"external_id\").notNull(),\n\taccessTokenCiphertext: text$1(\"access_token_ciphertext\").notNull(),\n\trefreshTokenCiphertext: text$1(\"refresh_token_ciphertext\"),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tgrantedScopes: text$1(\"granted_scopes\", { mode: \"json\" }).$type(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tconnectedAt: integer$1(\"connected_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"oauth_connections_app_external_unique\").on(table.appId, table.externalId), index$1(\"oauth_connections_external_id_idx\").on(table.externalId)]);\n//#endregion\n//#region src/schema/tables/organization-users.ts\nconst organizationUserRoles = [\n\t\"owner\",\n\t\"admin\",\n\t\"builder\"\n];\nconst organizationUsers = pgTable(\"organization_users\", {\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [primaryKey({ columns: [table.organizationId, table.userId] }), index(\"organization_users_user_id_idx\").on(table.userId)]);\nconst organizationUsersSqlite = sqliteTable(\"organization_users\", {\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [primaryKey$1({ columns: [table.organizationId, table.userId] }), index$1(\"organization_users_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/organization-invitations.ts\nconst organizationInvitationStatuses = [\n\t\"pending\",\n\t\"accepted\",\n\t\"declined\",\n\t\"revoked\"\n];\nconst organizationInvitations = pgTable(\"organization_invitations\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\temail: text(\"email\").notNull(),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type(),\n\tinvitedByUserId: text(\"invited_by_user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true })\n}, (table) => [\n\tindex(\"organization_invitations_user_id_idx\").on(table.userId),\n\tindex(\"organization_invitations_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"organization_invitations_org_user_pending_unique\").on(table.organizationId, table.userId).where(sql`${table.status} = 'pending'`)\n]);\nconst organizationInvitationsSqlite = sqliteTable(\"organization_invitations\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\temail: text$1(\"email\").notNull(),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type(),\n\tinvitedByUserId: text$1(\"invited_by_user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" })\n}, (table) => [\n\tindex$1(\"organization_invitations_user_id_idx\").on(table.userId),\n\tindex$1(\"organization_invitations_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"organization_invitations_org_user_pending_unique\").on(table.organizationId, table.userId).where(sql`${table.status} = 'pending'`)\n]);\n//#endregion\n//#region src/schema/tables/projects.ts\nconst projectStatuses = [\n\t\"inactive\",\n\t\"starting\",\n\t\"active\",\n\t\"failed\"\n];\nconst projectStatusEnum = pgEnum(\"project_status\", projectStatuses);\nconst projects = pgTable(\"projects\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tname: text(\"name\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tdescription: text(\"description\"),\n\tdefaultMemberRole: text(\"default_member_role\").notNull().$type().default(\"builder\"),\n\tinvitePermission: text(\"invite_permission\").notNull().$type().default(\"admin\"),\n\tcreatedByUserId: text(\"created_by_user_id\").references(() => users.id, { onDelete: \"set null\" }),\n\tstatus: projectStatusEnum(\"status\").notNull(),\n\tbaseUrl: text(\"base_url\"),\n\truntimeId: text(\"runtime_id\"),\n\tactiveArtifactId: text(\"active_artifact_id\"),\n\tpendingArtifactId: text(\"pending_artifact_id\"),\n\tlastError: text(\"last_error\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [index(\"projects_organization_id_idx\").on(table.organizationId), uniqueIndex(\"projects_organization_slug_unique\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`)]);\nconst projectsSqlite = sqliteTable(\"projects\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tname: text$1(\"name\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tdescription: text$1(\"description\"),\n\tdefaultMemberRole: text$1(\"default_member_role\").notNull().$type().default(\"builder\"),\n\tinvitePermission: text$1(\"invite_permission\").notNull().$type().default(\"admin\"),\n\tcreatedByUserId: text$1(\"created_by_user_id\").references(() => usersSqlite.id, { onDelete: \"set null\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tbaseUrl: text$1(\"base_url\"),\n\truntimeId: text$1(\"runtime_id\"),\n\tactiveArtifactId: text$1(\"active_artifact_id\"),\n\tpendingArtifactId: text$1(\"pending_artifact_id\"),\n\tlastError: text$1(\"last_error\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"projects_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"projects_organization_slug_unique\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`)]);\n//#endregion\n//#region src/schema/tables/project-artifacts.ts\nconst projectArtifactStatuses = [\"pending\", \"ready\"];\nconst projectArtifactStatusEnum = pgEnum(\"project_artifact_status\", projectArtifactStatuses);\nconst projectArtifacts = pgTable(\"project_artifacts\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tstorageKey: text(\"storage_key\").notNull(),\n\tmanifestJson: jsonb(\"manifest_json\"),\n\tsourceManifestJson: jsonb(\"source_manifest_json\"),\n\tversion: integer(\"version\").notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\").references(() => users.id, { onDelete: \"set null\" }),\n\tstatus: projectArtifactStatusEnum(\"status\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"project_artifacts_project_id_idx\").on(table.projectId)]);\nconst projectArtifactsSqlite = sqliteTable(\"project_artifacts\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tstorageKey: text$1(\"storage_key\").notNull(),\n\tmanifestJson: text$1(\"manifest_json\", { mode: \"json\" }),\n\tsourceManifestJson: text$1(\"source_manifest_json\", { mode: \"json\" }),\n\tversion: integer$1(\"version\").notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_id\").references(() => usersSqlite.id, { onDelete: \"set null\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"project_artifacts_project_id_idx\").on(table.projectId)]);\n//#endregion\n//#region src/schema/tables/project-users.ts\nconst projectUsers = pgTable(\"project_users\", {\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [primaryKey({ columns: [table.projectId, table.userId] }), index(\"project_users_user_id_idx\").on(table.userId)]);\nconst projectUsersSqlite = sqliteTable(\"project_users\", {\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [primaryKey$1({ columns: [table.projectId, table.userId] }), index$1(\"project_users_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/secret-values.ts\nconst secretValues = pgTable(\"secret_values\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\trefKind: text(\"ref_kind\").$type().notNull(),\n\trefId: text(\"ref_id\").notNull(),\n\tfield: text(\"field\").$type().notNull(),\n\tciphertext: text(\"ciphertext\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"secret_values_ref_unique\").on(table.organizationId, table.refKind, table.refId, table.field)]);\nconst secretValuesSqlite = sqliteTable(\"secret_values\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\trefKind: text$1(\"ref_kind\").$type().notNull(),\n\trefId: text$1(\"ref_id\").notNull(),\n\tfield: text$1(\"field\").$type().notNull(),\n\tciphertext: text$1(\"ciphertext\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"secret_values_ref_unique\").on(table.organizationId, table.refKind, table.refId, table.field)]);\n//#endregion\n//#region src/schema/registrations.ts\n/**\n* Platform control-plane tables — Postgres (hosted) or SQLite (local dev).\n*/\nconst tableRegistry = {\n\torganizations: {\n\t\tpg: organizations,\n\t\tsqlite: organizationsSqlite\n\t},\n\torganizationUsers: {\n\t\tpg: organizationUsers,\n\t\tsqlite: organizationUsersSqlite\n\t},\n\torganizationInvitations: {\n\t\tpg: organizationInvitations,\n\t\tsqlite: organizationInvitationsSqlite\n\t},\n\tprojects: {\n\t\tpg: projects,\n\t\tsqlite: projectsSqlite\n\t},\n\tprojectUsers: {\n\t\tpg: projectUsers,\n\t\tsqlite: projectUsersSqlite\n\t},\n\tprojectArtifacts: {\n\t\tpg: projectArtifacts,\n\t\tsqlite: projectArtifactsSqlite\n\t},\n\tusers: {\n\t\tpg: users,\n\t\tsqlite: usersSqlite\n\t},\n\tauthSessions: {\n\t\tpg: authSessions,\n\t\tsqlite: authSessionsSqlite\n\t},\n\tauthAccounts: {\n\t\tpg: authAccounts,\n\t\tsqlite: authAccountsSqlite\n\t},\n\tauthVerifications: {\n\t\tpg: authVerifications,\n\t\tsqlite: authVerificationsSqlite\n\t},\n\tauthDeviceCodes: {\n\t\tpg: authDeviceCodes,\n\t\tsqlite: authDeviceCodesSqlite\n\t},\n\tauthJwks: {\n\t\tpg: authJwks,\n\t\tsqlite: authJwksSqlite\n\t},\n\tauthApiKeys: {\n\t\tpg: authApiKeys,\n\t\tsqlite: authApiKeysSqlite\n\t},\n\tapps: {\n\t\tpg: apps,\n\t\tsqlite: appsSqlite\n\t},\n\toauthApps: {\n\t\tpg: oauthApps,\n\t\tsqlite: oauthAppsSqlite\n\t},\n\toauthConnections: {\n\t\tpg: oauthConnections,\n\t\tsqlite: oauthConnectionsSqlite\n\t},\n\tmcpOauthClient: {\n\t\tpg: mcpOauthClient,\n\t\tsqlite: mcpOauthClientSqlite\n\t},\n\tmcpOauthAccessToken: {\n\t\tpg: mcpOauthAccessToken,\n\t\tsqlite: mcpOauthAccessTokenSqlite\n\t},\n\tmcpOauthConsent: {\n\t\tpg: mcpOauthConsent,\n\t\tsqlite: mcpOauthConsentSqlite\n\t},\n\tsecretValues: {\n\t\tpg: secretValues,\n\t\tsqlite: secretValuesSqlite\n\t}\n};\nconst schema = buildPgSchema(tableRegistry);\nbuildSqliteSchema(tableRegistry);\n//#endregion\n//#region src/connection/pg/db.ts\n/** Inferred from `schema` — `getDb()` and query files use this type. */\nfunction createPgDb(pool) {\n\treturn loadDrizzlePg().drizzle(pool, { schema });\n}\n//#endregion\n//#region src/connection/pg/index.ts\nfunction createPgConnection(options) {\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst { Pool } = loadPg();\n\tconst pool = new Pool({\n\t\tconnectionString: options.url,\n\t\tmax: options.max ?? 10,\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath,\n\t\tclose: () => pool.end()\n\t};\n}\n//#endregion\n//#region src/connection/sqlite/index.ts\nfunction configureSqlite(client) {\n\tclient.pragma(\"journal_mode = WAL\");\n\tclient.pragma(\"foreign_keys = ON\");\n}\nfunction createSqliteConnection(options) {\n\tconst path = resolveSqlitePath(options.url);\n\tif (path !== \":memory:\") mkdirSync(dirname(path), { recursive: true });\n\tconst client = new BetterSqlite3(path);\n\tconfigureSqlite(client);\n\treturn {\n\t\tdialect: \"sqlite\",\n\t\tdb: drizzle(client, { schema }),\n\t\tclose: () => client.close()\n\t};\n}\n//#endregion\n//#region src/connection/create-connection.ts\nfunction createConnection(options) {\n\tif ((options.dialect ?? inferDialect(options.url)) === \"postgres\") return createPgConnection({\n\t\turl: options.url,\n\t\tmax: options.max,\n\t\tsearchPath: options.searchPath\n\t});\n\treturn createSqliteConnection({ url: options.url });\n}\n//#endregion\n//#region src/migrate/resolve-folder.ts\nfunction resolvePackageRoot() {\n\tlet dir = dirname(fileURLToPath(import.meta.url));\n\tfor (;;) {\n\t\tif (existsSync(join(dir, \"drizzle\", \"pg\", \"meta\", \"_journal.json\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tthrow new Error(\"Could not resolve @keystrokehq/platform-database package root for migrations\");\n}\nfunction resolveMigrationsFolder(dialect, override) {\n\tif (override) return override;\n\ttry {\n\t\treturn join(resolvePackageRoot(), \"drizzle\", dialect);\n\t} catch {\n\t\treturn join(dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"drizzle\", dialect);\n\t}\n}\n//#endregion\n//#region src/migrate/migrations.pg.generated.ts\nconst platformPgMigrations = [\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TYPE \\\"public\\\".\\\"project_artifact_status\\\" AS ENUM('pending', 'ready');\",\n\t\t\t\"\\nCREATE TYPE \\\"public\\\".\\\"project_status\\\" AS ENUM('inactive', 'starting', 'active', 'failed');\",\n\t\t\t\"\\nCREATE TABLE \\\"accounts\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"account_id\\\" text NOT NULL,\\n\t\\\"provider_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"access_token\\\" text,\\n\t\\\"refresh_token\\\" text,\\n\t\\\"id_token\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"refresh_token_expires_at\\\" timestamp with time zone,\\n\t\\\"scope\\\" text,\\n\t\\\"password\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"api_keys\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"config_id\\\" text DEFAULT 'default' NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"start\\\" text,\\n\t\\\"prefix\\\" text,\\n\t\\\"key\\\" text NOT NULL,\\n\t\\\"key_ciphertext\\\" text,\\n\t\\\"reference_id\\\" text NOT NULL,\\n\t\\\"refill_interval\\\" integer,\\n\t\\\"refill_amount\\\" integer,\\n\t\\\"last_refill_at\\\" timestamp with time zone,\\n\t\\\"enabled\\\" boolean DEFAULT true,\\n\t\\\"rate_limit_enabled\\\" boolean DEFAULT true,\\n\t\\\"rate_limit_time_window\\\" integer,\\n\t\\\"rate_limit_max\\\" integer,\\n\t\\\"request_count\\\" integer DEFAULT 0,\\n\t\\\"remaining\\\" integer,\\n\t\\\"last_request\\\" timestamp with time zone,\\n\t\\\"expires_at\\\" timestamp with time zone,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"permissions\\\" text,\\n\t\\\"metadata\\\" text\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"device_auth_codes\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"device_code\\\" text NOT NULL,\\n\t\\\"user_code\\\" text NOT NULL,\\n\t\\\"user_id\\\" text,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"last_polled_at\\\" timestamp with time zone,\\n\t\\\"polling_interval\\\" integer,\\n\t\\\"client_id\\\" text,\\n\t\\\"scope\\\" text\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"jwks\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"public_key\\\" text NOT NULL,\\n\t\\\"private_key\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"sessions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"token\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"ip_address\\\" text,\\n\t\\\"user_agent\\\" text,\\n\t\\\"user_id\\\" text NOT NULL,\\n\tCONSTRAINT \\\"sessions_token_unique\\\" UNIQUE(\\\"token\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"verification\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"identifier\\\" text NOT NULL,\\n\t\\\"value\\\" text NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"provider\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"token_strategy\\\" text NOT NULL,\\n\t\\\"client_id_ciphertext\\\" text NOT NULL,\\n\t\\\"client_secret_ciphertext\\\" text NOT NULL,\\n\t\\\"signing_secret_ciphertext\\\" text,\\n\t\\\"redirect_uri\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_connections\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"app_id\\\" text NOT NULL,\\n\t\\\"external_id\\\" text NOT NULL,\\n\t\\\"access_token_ciphertext\\\" text NOT NULL,\\n\t\\\"refresh_token_ciphertext\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"granted_scopes\\\" jsonb,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"connected_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organization_invitations\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"email\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"invited_by_user_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organization_users\\\" (\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text DEFAULT 'active' NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone,\\n\tCONSTRAINT \\\"organization_users_organization_id_user_id_pk\\\" PRIMARY KEY(\\\"organization_id\\\",\\\"user_id\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organizations\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"db_schema\\\" text NOT NULL,\\n\t\\\"db_user\\\" text NOT NULL,\\n\t\\\"db_password_ciphertext\\\" text NOT NULL,\\n\t\\\"hosting_app_name\\\" text,\\n\t\\\"storage_bucket\\\" text,\\n\t\\\"storage_endpoint\\\" text,\\n\t\\\"storage_access_key_id_ciphertext\\\" text,\\n\t\\\"storage_secret_access_key_ciphertext\\\" text,\\n\t\\\"storage_region\\\" text,\\n\t\\\"storage_force_path_style\\\" boolean,\\n\t\\\"custom_logo_enabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"custom_logo_explicitly_disabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"logo_light_url\\\" text,\\n\t\\\"logo_dark_url\\\" text,\\n\t\\\"logo_height_px\\\" integer DEFAULT 20 NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"project_artifacts\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"storage_key\\\" text NOT NULL,\\n\t\\\"manifest_json\\\" jsonb,\\n\t\\\"source_manifest_json\\\" jsonb,\\n\t\\\"version\\\" integer NOT NULL,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"status\\\" \\\"project_artifact_status\\\" NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"projects\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"description\\\" text,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"status\\\" \\\"project_status\\\" NOT NULL,\\n\t\\\"base_url\\\" text,\\n\t\\\"runtime_id\\\" text,\\n\t\\\"active_artifact_id\\\" text,\\n\t\\\"pending_artifact_id\\\" text,\\n\t\\\"last_error\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"secret_values\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"ref_kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"field\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"users\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"email\\\" text NOT NULL,\\n\t\\\"email_verified\\\" boolean NOT NULL,\\n\t\\\"image\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"users_email_unique\\\" UNIQUE(\\\"email\\\")\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"accounts\\\" ADD CONSTRAINT \\\"accounts_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"sessions\\\" ADD CONSTRAINT \\\"sessions_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_apps\\\" ADD CONSTRAINT \\\"oauth_apps_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_connections\\\" ADD CONSTRAINT \\\"oauth_connections_app_id_oauth_apps_id_fk\\\" FOREIGN KEY (\\\"app_id\\\") REFERENCES \\\"public\\\".\\\"oauth_apps\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_invited_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"invited_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_users\\\" ADD CONSTRAINT \\\"organization_users_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_users\\\" ADD CONSTRAINT \\\"organization_users_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD CONSTRAINT \\\"project_artifacts_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD CONSTRAINT \\\"project_artifacts_created_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"created_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE set null ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD CONSTRAINT \\\"projects_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD CONSTRAINT \\\"projects_created_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"created_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE set null ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"secret_values\\\" ADD CONSTRAINT \\\"secret_values_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"account_user_id_idx\\\" ON \\\"accounts\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_reference_id_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"reference_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_config_id_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"config_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_key_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"key\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"session_user_id_idx\\\" ON \\\"sessions\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"verification_identifier_idx\\\" ON \\\"verification\\\" USING btree (\\\"identifier\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_apps_organization_id_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"organization_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"oauth_apps_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_connections_app_external_unique\\\" ON \\\"oauth_connections\\\" USING btree (\\\"app_id\\\",\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"oauth_connections_external_id_idx\\\" ON \\\"oauth_connections\\\" USING btree (\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_invitations_user_id_idx\\\" ON \\\"organization_invitations\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_invitations_organization_id_idx\\\" ON \\\"organization_invitations\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"organization_invitations_org_user_pending_unique\\\" ON \\\"organization_invitations\\\" USING btree (\\\"organization_id\\\",\\\"user_id\\\") WHERE \\\"organization_invitations\\\".\\\"status\\\" = 'pending';\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_users_user_id_idx\\\" ON \\\"organization_users\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"organizations_slug_unique\\\" ON \\\"organizations\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"project_artifacts_project_id_idx\\\" ON \\\"project_artifacts\\\" USING btree (\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"projects_organization_id_idx\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"projects_org_auto_created_by_user_unique\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\",\\\"created_by_user_id\\\") WHERE \\\"projects\\\".\\\"created_by_user_id\\\" IS NOT NULL AND \\\"projects\\\".\\\"deleted_at\\\" IS NULL;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"projects_organization_slug_unique\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\",\\\"slug\\\") WHERE \\\"projects\\\".\\\"deleted_at\\\" IS NULL;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"secret_values_ref_unique\\\" ON \\\"secret_values\\\" USING btree (\\\"organization_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\",\\\"field\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"secret_values_ref_idx\\\" ON \\\"secret_values\\\" USING btree (\\\"organization_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781213647047,\n\t\t\"hash\": \"48e4b0a3b93c74edcdf88867eb21556327144131da0870bc764edee3e08560c1\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"users\\\" ADD COLUMN \\\"preferences\\\" jsonb;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781276711832,\n\t\t\"hash\": \"aa68be6edc75bf379abd0d5ce031ff60008fe881d7d785a996b002b63d424bc7\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"project_users\\\" (\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text DEFAULT 'active' NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone,\\n\tCONSTRAINT \\\"project_users_project_id_user_id_pk\\\" PRIMARY KEY(\\\"project_id\\\",\\\"user_id\\\")\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"default_member_role\\\" text DEFAULT 'builder' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"invite_permission\\\" text DEFAULT 'admin' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"project_users\\\" ADD CONSTRAINT \\\"project_users_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_users\\\" ADD CONSTRAINT \\\"project_users_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"project_users_user_id_idx\\\" ON \\\"project_users\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nINSERT INTO \\\"project_users\\\" (\\\"project_id\\\", \\\"user_id\\\", \\\"role\\\", \\\"status\\\", \\\"created_at\\\", \\\"updated_at\\\")\\nSELECT p.id, p.created_by_user_id, 'admin', 'active', NOW(), NOW()\\nFROM \\\"projects\\\" p\\nWHERE p.created_by_user_id IS NOT NULL AND p.deleted_at IS NULL\\nON CONFLICT (\\\"project_id\\\", \\\"user_id\\\") DO NOTHING;\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 178128e7,\n\t\t\"hash\": \"d8809c81a5d2340d8651c36dfddad9427f039ac1481d3d0b3dcd63a73a79d11a\"\n\t},\n\t{\n\t\t\"sql\": [\"DELETE FROM \\\"project_users\\\" AS pu\\nUSING \\\"projects\\\" AS p, \\\"organization_users\\\" AS ou\\nWHERE pu.project_id = p.id\\n  AND pu.user_id = ou.user_id\\n  AND ou.organization_id = p.organization_id\\n  AND ou.role = 'builder'\\n  AND pu.role = 'builder'\\n  AND pu.user_id IS DISTINCT FROM p.created_by_user_id;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17812836e5,\n\t\t\"hash\": \"a025effc73d9ea3e21e734834a60a74f9e2b84c558eeef2c1bd18fd0311f8c5c\"\n\t},\n\t{\n\t\t\"sql\": [\"DROP INDEX IF EXISTS \\\"projects_org_auto_created_by_user_unique\\\";\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17812872e5,\n\t\t\"hash\": \"51ceed699b982b1ea96119e6ca7261a5e2ca854c456b7b89c65736a91114e1a6\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"description\\\" text NOT NULL,\\n\t\\\"category\\\" text NOT NULL,\\n\t\\\"logo\\\" text,\\n\t\\\"auth_kind\\\" text NOT NULL,\\n\t\\\"oauth_scopes\\\" jsonb NOT NULL,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"apps\\\" ADD CONSTRAINT \\\"apps_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"apps_slug_idx\\\" ON \\\"apps\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"apps_organization_id_idx\\\" ON \\\"apps\\\" USING btree (\\\"organization_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781819893736,\n\t\t\"hash\": \"22be601d95e9d4dd557036fd150112e7f05e98f33d0a99315aabd4739d1730b0\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"runtime_id\\\" text;\", \"\\nALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"base_url\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781990311400,\n\t\t\"hash\": \"41b6a62e955cf3accd8292902c3762f01712dc3a6068388edcc42b66b4c1d6a0\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"apps\\\" ADD COLUMN \\\"credential_fields\\\" jsonb DEFAULT '{}'::jsonb NOT NULL;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782105700654,\n\t\t\"hash\": \"063e3b85fb5a17325381bfd0425edc0b8ee8cbf0677c390fa67a7e52b7e758c2\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"verified_at\\\" timestamp with time zone;\", \"\\nUPDATE \\\"organizations\\\" SET \\\"verified_at\\\" = \\\"created_at\\\" WHERE \\\"verified_at\\\" IS NULL;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782144854087,\n\t\t\"hash\": \"316191ff040fe6d2b4de9b49d6d0de8a607ab87660bbdfbd9b697aaf387f5e1b\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"apps\\\" ADD COLUMN \\\"credential_scheme\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782409311909,\n\t\t\"hash\": \"6f345d63c2bab17b2eb9b9726b07d8523f1e1b1bad73001f07ceb4f2eee54326\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"mcp_oauth_access_token\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"access_token\\\" text NOT NULL,\\n\t\\\"refresh_token\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"refresh_token_expires_at\\\" timestamp with time zone,\\n\t\\\"client_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text,\\n\t\\\"scopes\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"mcp_oauth_access_token_access_token_unique\\\" UNIQUE(\\\"access_token\\\"),\\n\tCONSTRAINT \\\"mcp_oauth_access_token_refresh_token_unique\\\" UNIQUE(\\\"refresh_token\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"mcp_oauth_client\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"icon\\\" text,\\n\t\\\"metadata\\\" text,\\n\t\\\"client_id\\\" text NOT NULL,\\n\t\\\"client_secret\\\" text,\\n\t\\\"redirect_urls\\\" text NOT NULL,\\n\t\\\"type\\\" text NOT NULL,\\n\t\\\"disabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"user_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"mcp_oauth_client_client_id_unique\\\" UNIQUE(\\\"client_id\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"mcp_oauth_consent\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"client_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"scopes\\\" text,\\n\t\\\"consent_given\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"mcp_oauth_access_token\\\" ADD CONSTRAINT \\\"mcp_oauth_access_token_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"mcp_oauth_client\\\" ADD CONSTRAINT \\\"mcp_oauth_client_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"mcp_oauth_consent\\\" ADD CONSTRAINT \\\"mcp_oauth_consent_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_access_token_client_id_idx\\\" ON \\\"mcp_oauth_access_token\\\" USING btree (\\\"client_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_access_token_user_id_idx\\\" ON \\\"mcp_oauth_access_token\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_client_user_id_idx\\\" ON \\\"mcp_oauth_client\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_consent_client_id_idx\\\" ON \\\"mcp_oauth_consent\\\" USING btree (\\\"client_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_consent_user_id_idx\\\" ON \\\"mcp_oauth_consent\\\" USING btree (\\\"user_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782492431786,\n\t\t\"hash\": \"7253f63af93f3e5666ef069762be85bf338e646ff59ecbe154e161317b54e5a1\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"apps\\\" ADD COLUMN \\\"mcp_url\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782507417125,\n\t\t\"hash\": \"23ce50823d9a3509f8fab79640ae554585f2789913592e918c76eee291f0dd9c\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"apps\\\" ADD COLUMN IF NOT EXISTS \\\"url\\\" text;\",\n\t\t\t\"\\nUPDATE \\\"apps\\\" SET \\\"url\\\" = \\\"mcp_url\\\" WHERE \\\"url\\\" IS NULL AND \\\"mcp_url\\\" IS NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"apps\\\" DROP COLUMN IF EXISTS \\\"mcp_url\\\";\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 178251e7,\n\t\t\"hash\": \"470832e835329b20d4b22f83f3103869e94effd66de83bc573001d603a5c87b1\"\n\t},\n\t{\n\t\t\"sql\": [\"DROP INDEX \\\"secret_values_ref_idx\\\";\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782679241250,\n\t\t\"hash\": \"95263d7c86d9b02c9d0c1a9233227cb449f500ae523d8423eb2b829bfa39f7cf\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"redis_url_ciphertext\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782847877006,\n\t\t\"hash\": \"79321e24c3a532a301ad4924722ff43d32bd85d2324e5f3079fccfecf4084692\"\n\t}\n];\n//#endregion\n//#region src/migrate/run.ts\nasync function runMigrations(handle, migrationsFolder) {\n\tif (handle.dialect === \"sqlite\") {\n\t\tmigrate(handle.db, { migrationsFolder });\n\t\treturn;\n\t}\n\tconst config = {\n\t\tmigrationsFolder,\n\t\tmigrationsSchema: resolveMigrationsSchema(handle.searchPath)\n\t};\n\tconst loaded = loadMigrations(migrationsFolder, platformPgMigrations);\n\tconst migrations = handle.searchPath ? adaptPgMigrationsForSearchPath(loaded) : loaded;\n\tawait migratePgDatabase(handle.db, config, migrations);\n}\n//#endregion\n//#region src/client/init.ts\nfunction resolveUrl(url) {\n\treturn url ?? resolvePlatformDatabaseUrl();\n}\nfunction wrapPlatformPostgresHandle(base) {\n\tconst pool = createPublicScopedPool(base.pool);\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath: \"public\",\n\t\tclose: base.close\n\t};\n}\nasync function initDatabase(options = {}) {\n\tif (isDatabaseInitialized()) return;\n\tconst url = resolveUrl(options.url);\n\tconst dialect = options.dialect ?? inferDialect(url);\n\tconst searchPath = dialect === \"postgres\" ? resolveSearchPath(url, options.searchPath) : void 0;\n\tconst base = createConnection({\n\t\turl,\n\t\tdialect,\n\t\tmax: options.max,\n\t\tsearchPath\n\t});\n\tconst next = base.dialect === \"postgres\" ? wrapPlatformPostgresHandle(base) : base;\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n}\n//#endregion\n//#region src/config/organization-scope.ts\nconst organizationScopeStorage = new AsyncLocalStorage();\nfunction runWithOrganizationScope(organizationId, fn) {\n\treturn organizationScopeStorage.run(organizationId, fn);\n}\nfunction getOrganizationScopeId() {\n\treturn organizationScopeStorage.getStore();\n}\nfunction requireOrganizationScopeId() {\n\tconst organizationId = getOrganizationScopeId();\n\tif (!organizationId) throw new Error(\"Organization scope is not set\");\n\treturn organizationId;\n}\n//#endregion\n//#region src/project-database/build-url.ts\n/** Org DB connection options for `@keystrokehq/database` tenant scope. */\nfunction resolveOrgProjectDatabaseOptions(organization, env = process.env) {\n\tconst platformUrl = resolvePlatformDatabaseUrl(env);\n\tif (inferDialect(platformUrl) === \"postgres\") return {\n\t\turl: platformUrl,\n\t\trole: organization.dbUser,\n\t\tsearchPath: organization.dbSchema\n\t};\n\treturn { url: organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}` };\n}\nfunction buildOrgDatabaseUrl(user, password, env = process.env) {\n\treturn buildPostgresUrl({\n\t\t...resolvePlatformPostgresConfig(env),\n\t\tuser: qualifyConnectionUser(user, env),\n\t\tpassword\n\t});\n}\nfunction resolveOrgDatabaseUrl(organization, env = process.env) {\n\tif (inferDialect(resolvePlatformDatabaseUrl(env)) === \"sqlite\") return organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}`;\n\tconst password = decryptCredentialPayload$1(organization.dbPasswordCiphertext);\n\treturn buildOrgDatabaseUrl(organization.dbUser, password, env);\n}\n//#endregion\n//#region src/project-database/names.ts\nfunction sanitizeIdForPgIdent(id) {\n\treturn id.replace(/-/g, \"_\");\n}\n/**\n* Per-org sqlite db lives beside the platform (public) sqlite db so that each\n* standalone instance / test working directory is isolated. Falls back to\n* `<cwd>/data` when the platform db is in-memory or not a file URL.\n*/\nfunction orgDbFilePath(organizationId) {\n\tconst standaloneDataDir = process.env.KEYSTROKE_STANDALONE_DATA_DIR?.trim();\n\tif (standaloneDataDir) return join(standaloneDataDir, `org_${sanitizeIdForPgIdent(organizationId)}.db`);\n\tconst platformPath = resolveSqlitePath(resolvePlatformDatabaseUrl());\n\treturn join(platformPath !== \"\" && !platformPath.startsWith(\":memory:\") ? dirname(platformPath) : join(process.cwd(), \"data\"), `org_${sanitizeIdForPgIdent(organizationId)}.db`);\n}\nfunction orgDbSchemaName(organizationId) {\n\tconst name = `org_${sanitizeIdForPgIdent(organizationId)}`;\n\tassertPgIdent(name);\n\treturn name;\n}\nfunction orgDbRoleName(organizationId) {\n\tconst name = `org_${sanitizeIdForPgIdent(organizationId)}_user`;\n\tassertPgIdent(name);\n\treturn name;\n}\n/** Deterministic Redis ACL username for an org (mirrors orgDbRoleName without _user suffix). */\nfunction orgRedisUsername(organizationId) {\n\treturn `org_${sanitizeIdForPgIdent(organizationId)}`;\n}\n/** BullMQ queue segment — colons forbidden in queue names. */\nfunction orgRedisQueueSegment(organizationId) {\n\treturn organizationId.replaceAll(\":\", \"-\");\n}\n//#endregion\n//#region src/project-database/grant-platform-login.ts\n/**\n* Strip the PlanetScale `<role>.<branch>` connection suffix to the underlying\n* Postgres role. Providers like PlanetScale authenticate as `postgres` but expose\n* the credential as `postgres.<branchId>`; GRANT targets the real role name.\n*/\nfunction basePostgresRole(user) {\n\tconst dot = user.lastIndexOf(\".\");\n\treturn dot > 0 ? user.slice(0, dot) : user;\n}\n/** Postgres role from the platform DATABASE_URL — shared login for tenant SET LOCAL ROLE. */\nfunction resolvePlatformLoginRole(env = process.env) {\n\tif (inferDialect(resolvePlatformDatabaseUrl(env)) !== \"postgres\") return;\n\treturn basePostgresRole(resolvePlatformPostgresConfig(env).user);\n}\n/** Grant org role membership to the platform DATABASE_URL role (no table privileges). */\nasync function grantOrgRoleToPlatformLogin(pool, orgRole, env = process.env) {\n\tconst platformLoginRole = resolvePlatformLoginRole(env);\n\tif (!platformLoginRole) return;\n\tconst orgRoleIdent = quotePgIdent(orgRole);\n\tconst platformLoginIdent = quotePgIdent(platformLoginRole);\n\tawait pool.query(`GRANT ${orgRoleIdent} TO ${platformLoginIdent} WITH INHERIT FALSE`);\n}\n//#endregion\n//#region src/project-database/pgboss-grants.ts\nasync function grantPgBossAccess(pool, dbUser) {\n\tconst roleIdent = quotePgIdent(dbUser);\n\tconst { rows } = await pool.query(`SELECT EXISTS (\n      SELECT 1 FROM information_schema.schemata WHERE schema_name = 'pgboss'\n    ) AS exists`);\n\tif (!rows[0]?.exists) return;\n\tawait pool.query(`GRANT USAGE ON SCHEMA pgboss TO ${roleIdent}`);\n\tawait pool.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA pgboss TO ${roleIdent}`);\n\tawait pool.query(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA pgboss TO ${roleIdent}`);\n}\n//#endregion\n//#region src/project-database/provision.ts\nasync function provisionOrgDatabaseSqlite(organizationId) {\n\tconst dbSchema = orgDbFilePath(organizationId);\n\tmkdirSync(dirname(dbSchema), { recursive: true });\n\tconst handle = createConnection$1({\n\t\turl: `file:${dbSchema}`,\n\t\tdialect: \"sqlite\"\n\t});\n\ttry {\n\t\tawait runMigrations$1(handle, resolveMigrationsFolder$1(\"sqlite\"));\n\t} finally {\n\t\thandle.close();\n\t}\n\treturn {\n\t\tdbSchema,\n\t\tdbUser: \"\",\n\t\tdbPasswordCiphertext: \"\"\n\t};\n}\nasync function quoteLiteral(pool, value) {\n\tconst { rows } = await pool.query(\"SELECT quote_literal($1) AS quoted\", [value]);\n\tconst quoted = rows[0]?.quoted;\n\tif (!quoted) throw new Error(\"Failed to quote Postgres literal\");\n\treturn quoted;\n}\nasync function grantOrgSchemaObjects(pool, dbSchema, dbUser) {\n\tconst schemaIdent = quotePgIdent(dbSchema);\n\tconst roleIdent = quotePgIdent(dbUser);\n\tawait pool.query(`GRANT ALL ON ALL TABLES IN SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\tawait pool.query(`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\tawait pool.query(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${schemaIdent} GRANT ALL ON TABLES TO ${roleIdent}`);\n\tawait pool.query(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${schemaIdent} GRANT ALL ON SEQUENCES TO ${roleIdent}`);\n\tconst { rows } = await pool.query(`SELECT n.nspname, t.typname\n     FROM pg_type t\n     JOIN pg_namespace n ON n.oid = t.typnamespace\n     WHERE n.nspname = $1 AND t.typtype = 'e'`, [dbSchema]);\n\tfor (const row of rows) {\n\t\tconst typeIdent = `${quotePgIdent(row.nspname)}.${quotePgIdent(row.typname)}`;\n\t\tawait pool.query(`GRANT USAGE ON TYPE ${typeIdent} TO ${roleIdent}`);\n\t}\n}\nasync function provisionOrgDatabasePostgres(organizationId) {\n\tconst dbSchema = orgDbSchemaName(organizationId);\n\tconst dbUser = orgDbRoleName(organizationId);\n\tconst password = randomBytes(32).toString(\"base64url\");\n\tconst databaseUrl = resolvePlatformDatabaseUrl();\n\tconst { Pool: PgPool } = loadPg();\n\tconst pool = new PgPool({ connectionString: databaseUrl });\n\ttry {\n\t\tconst quotedPassword = await quoteLiteral(pool, password);\n\t\tconst schemaIdent = quotePgIdent(dbSchema);\n\t\tconst roleIdent = quotePgIdent(dbUser);\n\t\tawait pool.query(`CREATE ROLE ${roleIdent} WITH LOGIN PASSWORD ${quotedPassword}`);\n\t\tawait pool.query(`REVOKE CREATE ON SCHEMA public FROM PUBLIC`);\n\t\tawait pool.query(`REVOKE ALL ON SCHEMA public FROM ${roleIdent}`);\n\t\tawait pool.query(`CREATE SCHEMA ${schemaIdent}`);\n\t\tawait pool.query(`GRANT ALL ON SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\t\tconst { rows: dbRows } = await pool.query(\"SELECT current_database() AS name\");\n\t\tconst databaseName = dbRows[0]?.name;\n\t\tif (!databaseName) throw new Error(\"Failed to resolve current database name\");\n\t\tawait pool.query(`GRANT CREATE ON DATABASE ${quotePgIdent(databaseName)} TO ${roleIdent}`);\n\t\tawait pool.query(`ALTER ROLE ${roleIdent} SET search_path TO ${schemaIdent}`);\n\t\tawait grantPgBossAccess(pool, dbUser);\n\t\tawait grantOrgRoleToPlatformLogin(pool, dbUser);\n\t\tconst handle = createConnection$1({\n\t\t\turl: buildOrgDatabaseUrl(dbUser, password),\n\t\t\tdialect: \"postgres\",\n\t\t\tsearchPath: dbSchema\n\t\t});\n\t\ttry {\n\t\t\tawait runMigrations$1(handle, resolveMigrationsFolder$1(\"postgres\"));\n\t\t} finally {\n\t\t\tawait handle.close();\n\t\t}\n\t\tawait grantOrgSchemaObjects(pool, dbSchema, dbUser);\n\t\treturn {\n\t\t\tdbSchema,\n\t\t\tdbUser,\n\t\t\tdbPasswordCiphertext: encryptCredentialPayload$1(password)\n\t\t};\n\t} catch (error) {\n\t\tawait deprovisionOrgDatabase({\n\t\t\tdbSchema,\n\t\t\tdbUser\n\t\t}).catch(() => void 0);\n\t\tthrow error;\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\nasync function provisionOrgDatabase(organizationId) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") return provisionOrgDatabaseSqlite(organizationId);\n\treturn provisionOrgDatabasePostgres(organizationId);\n}\nasync function deprovisionOrgDatabase(input) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") {\n\t\ttry {\n\t\t\tunlinkSync(input.dbSchema);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tconst { Pool: PgPool } = loadPg();\n\tconst pool = new PgPool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst roleIdent = quotePgIdent(input.dbUser);\n\t\tawait pool.query(`DROP SCHEMA IF EXISTS ${quotePgIdent(input.dbSchema)} CASCADE`);\n\t\tif (input.dbUser) {\n\t\t\tawait pool.query(`DROP OWNED BY ${roleIdent}`);\n\t\t\tawait pool.query(`DROP ROLE IF EXISTS ${roleIdent}`);\n\t\t}\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n//#endregion\n//#region src/project-database/redis-provision.ts\nconst DEFAULT_QUEUE_PREFIX = \"keystroke\";\nfunction resolveAdminRedisUrl(env = process.env) {\n\treturn env.UPSTASH_REDIS_URL?.trim() || env.REDIS_URL?.trim() || void 0;\n}\nfunction resolveQueuePrefix(env = process.env) {\n\treturn env.KEYSTROKE_QUEUE_PREFIX?.trim() || DEFAULT_QUEUE_PREFIX;\n}\n/** Swap org ACL credentials into the shared admin Redis URL (preserves host/port/TLS). */\nfunction buildOrgRedisUrl(adminUrl, username, password) {\n\tconst url = new URL(adminUrl);\n\turl.username = username;\n\turl.password = password;\n\treturn url.toString();\n}\n/** Upstash Fly Redis rejects arbitrary `>password` modifiers — passwords must come from ACL GENTOKEN. */\nfunction usesUpstashGentokenPassword(adminUrl) {\n\ttry {\n\t\treturn new URL(adminUrl).hostname.endsWith(\".upstash.io\");\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** ACL permission rules for a tenant-scoped org user (keys + cancel channel only). */\nfunction orgRedisAclPermissionRules(organizationId, env = process.env) {\n\tconst queueSegment = orgRedisQueueSegment(organizationId);\n\tconst prefix = resolveQueuePrefix(env);\n\treturn [\n\t\t`~${prefix}:org-${queueSegment}:*`,\n\t\t`&${prefix}:cancel:org-${queueSegment}`,\n\t\t`~as:${organizationId}:*`,\n\t\t\"+@all\",\n\t\t\"-@admin\",\n\t\t\"-@dangerous\",\n\t\t\"+info\"\n\t];\n}\n/** ACL SETUSER args for a tenant-scoped org user (keys + cancel channel only). */\nfunction orgRedisAclSetUserArgs(organizationId, password, env = process.env) {\n\treturn [\n\t\t\"SETUSER\",\n\t\torgRedisUsername(organizationId),\n\t\t\"reset\",\n\t\t\"on\",\n\t\t`>${password}`,\n\t\t...orgRedisAclPermissionRules(organizationId, env)\n\t];\n}\nasync function resolveOrgRedisPassword(admin, organizationId, adminUrl) {\n\tconst username = orgRedisUsername(organizationId);\n\tif (usesUpstashGentokenPassword(adminUrl)) return String(await admin.call(\"ACL\", \"GENTOKEN\", username));\n\treturn randomBytes(32).toString(\"base64url\");\n}\nasync function provisionOrgRedis(organizationId, env = process.env) {\n\tconst adminUrl = resolveAdminRedisUrl(env);\n\tif (!adminUrl) return { redisUrlCiphertext: \"\" };\n\tconst username = orgRedisUsername(organizationId);\n\tconst admin = new Redis(adminUrl);\n\ttry {\n\t\tconst password = await resolveOrgRedisPassword(admin, organizationId, adminUrl);\n\t\tawait admin.call(\"ACL\", \"SETUSER\", username, \"reset\", \"on\", `>${password}`, ...orgRedisAclPermissionRules(organizationId, env));\n\t\treturn { redisUrlCiphertext: encryptCredentialPayload$1(buildOrgRedisUrl(adminUrl, username, password)) };\n\t} finally {\n\t\tawait admin.quit().catch(() => void 0);\n\t}\n}\nasync function deprovisionOrgRedis(organizationId, env = process.env) {\n\tconst adminUrl = resolveAdminRedisUrl(env);\n\tif (!adminUrl) return;\n\tconst admin = new Redis(adminUrl);\n\ttry {\n\t\tawait admin.call(\"ACL\", \"DELUSER\", orgRedisUsername(organizationId));\n\t} finally {\n\t\tawait admin.quit().catch(() => void 0);\n\t}\n}\n//#endregion\n//#region src/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb() {\n\treturn getDbFromContext();\n}\nfunction isSqliteDialect() {\n\treturn getDatabaseHandle().dialect === \"sqlite\";\n}\n/** Drizzle sqlite handle when the control-plane runs on sqlite. */\nfunction getSqliteDb() {\n\treturn getDbFromContext();\n}\n//#endregion\n//#region src/queries/users/email.ts\nfunction normalizeUserEmail(email) {\n\treturn email.trim().toLowerCase();\n}\nfunction placeholderNameFromEmail(email) {\n\tconst localPart = email.split(\"@\")[0]?.trim();\n\treturn localPart && localPart.length > 0 ? localPart : \"User\";\n}\n//#endregion\n//#region src/queries/users/index.ts\nasync function selectUserByNormalizedEmail(email) {\n\tconst normalized = normalizeUserEmail(email);\n\treturn (await getDb().select().from(users).where(sql$1`lower(${users.email}) = ${normalized}`).limit(1))[0];\n}\nasync function selectUserByEmail(email) {\n\treturn selectUserByNormalizedEmail(email);\n}\nasync function findOrCreateUserByEmail(email) {\n\tconst normalized = normalizeUserEmail(email);\n\tconst existing = await selectUserByNormalizedEmail(normalized);\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst db = getDb();\n\ttry {\n\t\tconst [created] = await db.insert(users).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\tname: placeholderNameFromEmail(normalized),\n\t\t\temail: normalized,\n\t\t\temailVerified: false,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning();\n\t\tif (!created) throw new Error(\"Failed to create user\");\n\t\treturn created;\n\t} catch (error) {\n\t\tconst raced = await selectUserByNormalizedEmail(normalized);\n\t\tif (raced) return raced;\n\t\tthrow error;\n\t}\n}\nasync function selectUserById(id) {\n\treturn (await getDb().select().from(users).where(eq$1(users.id, id)).limit(1))[0];\n}\nasync function selectUsersByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(users).where(inArray$1(users.id, ids));\n}\nasync function updateUserById(id, values) {\n\tawait getDb().update(users).set(values).where(eq$1(users.id, id));\n}\n//#endregion\n//#region src/queries/projects/slug.ts\nvar ProjectSlugTakenError = class extends Error {\n\tconstructor() {\n\t\tsuper(PROJECT_SLUG_TAKEN_MESSAGE);\n\t\tthis.name = \"ProjectSlugTakenError\";\n\t}\n};\nfunction isProjectSlugUniqueViolation(error) {\n\tif (typeof error !== \"object\" || error === null) return false;\n\treturn (\"code\" in error ? String(error.code) : \"\") === \"23505\";\n}\nasync function isProjectSlugTaken(executor, organizationId, slug, excludeProjectId) {\n\treturn (await executor.select({ id: projects.id }).from(projects).where(and(eq(projects.organizationId, organizationId), eq(projects.slug, slug), isNull(projects.deletedAt), excludeProjectId ? ne(projects.id, excludeProjectId) : void 0)).limit(1)).length > 0;\n}\nasync function resolveAvailableProjectSlug(executor, organizationId, name) {\n\tconst base = slugifyProjectName(name);\n\tif (!await isProjectSlugTaken(executor, organizationId, base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = ProjectSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isProjectSlugTaken(executor, organizationId, candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique project slug\");\n}\nasync function checkProjectSlugAvailability(organizationId, slug, excludeProjectId) {\n\tconst normalized = slug.trim().toLowerCase();\n\tconst format = ProjectSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (await isProjectSlugTaken(getDb(), organizationId, parsed, excludeProjectId)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableProjectSlug(getDb(), organizationId, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\n//#endregion\n//#region src/queries/projects/default-project.ts\n/** e.g. Alex → Alex's, Wells → Wells' */\nfunction formatPossessive(name) {\n\treturn name.endsWith(\"s\") || name.endsWith(\"S\") ? `${name}'` : `${name}'s`;\n}\n/** Auto-created projects only — not used for manual `POST /api/projects`. */\nfunction buildDefaultProjectDescription(displayName) {\n\treturn `${formatPossessive(displayName)} personal project for agents, workflows, and other stuff.`;\n}\nfunction firstNameFromUser(user) {\n\tconst fromName = user.name.trim().split(/\\s+/)[0];\n\tif (fromName) return fromName;\n\tconst local = user.email.split(\"@\")[0]?.replace(/[._+-]/g, \" \").trim();\n\treturn local && local.length > 0 ? local : \"My\";\n}\nfunction buildDefaultProjectForUser(user) {\n\tconst firstName = firstNameFromUser(user);\n\treturn {\n\t\tname: `${formatPossessive(firstName)} Project`,\n\t\tdescription: buildDefaultProjectDescription(firstName)\n\t};\n}\nasync function selectAutoCreatedProjectForUser(executor, organizationId, userId) {\n\treturn (await executor.select().from(projects).where(and$1(eq$1(projects.organizationId, organizationId), eq$1(projects.createdByUserId, userId), isNull$1(projects.deletedAt))).limit(1))[0];\n}\nasync function insertAutoCreatedProject(executor, organizationId, userId, name, description) {\n\tconst existing = await selectAutoCreatedProjectForUser(executor, organizationId, userId);\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst projectId = crypto.randomUUID();\n\tconst slug = await resolveAvailableProjectSlug(executor, organizationId, name);\n\tconst [inserted] = await executor.insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname,\n\t\tslug,\n\t\tdescription,\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tcreatedByUserId: userId,\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (inserted) {\n\t\tawait executor.insert(projectUsers).values({\n\t\t\tprojectId: inserted.id,\n\t\t\tuserId,\n\t\t\trole: \"admin\",\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).onConflictDoNothing();\n\t\treturn inserted;\n\t}\n\treturn selectAutoCreatedProjectForUser(executor, organizationId, userId);\n}\n/**\n* Creates the user's personal default project in `organizationId` when they do\n* not already have an auto-created project there.\n*/\nasync function ensureDefaultProjectForUserInTransaction(tx, userId, organizationId) {\n\tconst user = await selectUserById(userId);\n\tif (!user) throw new Error(\"User not found\");\n\tconst { name, description } = buildDefaultProjectForUser(user);\n\treturn insertAutoCreatedProject(tx, organizationId, userId, name, description);\n}\nasync function ensureDefaultProjectForUser(userId, organizationId) {\n\tconst user = await selectUserById(userId);\n\tif (!user) throw new Error(\"User not found\");\n\tconst { name, description } = buildDefaultProjectForUser(user);\n\treturn insertAutoCreatedProject(getDb(), organizationId, userId, name, description);\n}\n//#endregion\n//#region src/queries/organizations/slug.ts\nasync function checkOrganizationSlugAvailability(slug, excludeOrganizationId) {\n\tconst normalized = slug.trim().toLowerCase();\n\tconst format = OrganizationSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (RESERVED_ORGANIZATION_SLUGS.has(parsed)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"reserved\"\n\t};\n\tif (await isOrganizationSlugTaken(parsed, excludeOrganizationId)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableOrganizationSlug(parsed, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\nasync function isOrganizationSlugTaken(slug, excludeOrganizationId) {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(excludeOrganizationId ? and(eq(organizations.slug, slug), ne(organizations.id, excludeOrganizationId)) : eq(organizations.slug, slug)).limit(1)).length > 0;\n}\nfunction normalizeOrganizationSlugInput(name, slug) {\n\tif (slug?.trim()) {\n\t\tconst normalized = slug.trim().toLowerCase();\n\t\tif (normalized === slugifyOrganizationName(name)) return OrganizationSlugSchema.parse(normalized);\n\t\treturn ClaimableOrganizationSlugSchema.parse(normalized);\n\t}\n\treturn OrganizationSlugSchema.parse(slugifyOrganizationName(name));\n}\nasync function resolveAvailableOrganizationSlug(name, preferredSlug) {\n\tconst base = normalizeOrganizationSlugInput(name, preferredSlug);\n\tif (!RESERVED_ORGANIZATION_SLUGS.has(base) && !await isOrganizationSlugTaken(base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = OrganizationSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isOrganizationSlugTaken(candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique organization slug\");\n}\n//#endregion\n//#region src/queries/organizations/branding.ts\nfunction organizationRowToSidebarBranding(organization) {\n\treturn normalizeOrganizationSidebarBranding({\n\t\tcustomLogoEnabled: organization.customLogoEnabled,\n\t\tcustomLogoExplicitlyDisabled: organization.customLogoExplicitlyDisabled,\n\t\tlogoLightUrl: organization.logoLightUrl,\n\t\tlogoDarkUrl: organization.logoDarkUrl,\n\t\tlogoHeightPx: organization.logoHeightPx\n\t});\n}\nasync function updateOrganizationSidebarBranding(organizationId, input) {\n\tconst db = getDb();\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (input.customLogoEnabled !== void 0) updates.customLogoEnabled = input.customLogoEnabled;\n\tif (input.customLogoExplicitlyDisabled !== void 0) updates.customLogoExplicitlyDisabled = input.customLogoExplicitlyDisabled;\n\tif (input.logoLightUrl !== void 0) updates.logoLightUrl = input.logoLightUrl;\n\tif (input.logoDarkUrl !== void 0) updates.logoDarkUrl = input.logoDarkUrl;\n\tif (input.logoHeightPx !== void 0) updates.logoHeightPx = input.logoHeightPx;\n\tconst [organization] = await db.update(organizations).set(updates).where(eq(organizations.id, organizationId)).returning();\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\treturn organization;\n}\n//#endregion\n//#region src/queries/organizations/index.ts\nfunction userOrganizationSelect() {\n\treturn {\n\t\torganization: organizations,\n\t\trole: organizationUsers.role\n\t};\n}\nasync function selectOrganizationById(id) {\n\treturn (await getDb().select().from(organizations).where(eq(organizations.id, id)).limit(1))[0];\n}\nasync function selectOrganizationBySlug(slug) {\n\treturn (await getDb().select().from(organizations).where(eq(organizations.slug, slug)).limit(1))[0];\n}\nasync function isOrganizationStorageBucketInUse(bucket) {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(and(eq(organizations.storageBucket, bucket), isNull(organizations.deletedAt))).limit(1)).length > 0;\n}\nasync function selectActiveOrganizationIds() {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(isNull(organizations.deletedAt))).map((row) => row.id);\n}\nfunction activeOrganizationUserFilter(userId, organizationId) {\n\tconst clauses = [\n\t\teq(organizationUsers.userId, userId),\n\t\teq(organizationUsers.status, \"active\"),\n\t\tisNull(organizationUsers.deletedAt)\n\t];\n\tif (organizationId) clauses.push(eq(organizationUsers.organizationId, organizationId));\n\treturn and(...clauses);\n}\nasync function selectUserOrganizations(userId) {\n\treturn getDb().select(userOrganizationSelect()).from(organizationUsers).innerJoin(organizations, eq(organizationUsers.organizationId, organizations.id)).where(activeOrganizationUserFilter(userId));\n}\nasync function selectUserOrganization(userId) {\n\treturn (await selectUserOrganizations(userId))[0];\n}\nasync function selectUserOrganizationMembership(userId, organizationId) {\n\treturn (await getDb().select(userOrganizationSelect()).from(organizationUsers).innerJoin(organizations, eq(organizationUsers.organizationId, organizations.id)).where(activeOrganizationUserFilter(userId, organizationId)).limit(1))[0];\n}\nasync function updateOrganizationActive(organizationId, input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(organizations).set({\n\t\tbaseUrl: input.baseUrl,\n\t\truntimeId: input.runtimeId,\n\t\tupdatedAt: now\n\t}).where(eq(organizations.id, organizationId)).returning())[0];\n}\nasync function updateOrganizationFailed(organizationId, _lastError) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(organizations).set({ updatedAt: now }).where(eq(organizations.id, organizationId)).returning())[0];\n}\nasync function updateOrganizationName(organizationId, name) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [organization] = await db.update(organizations).set({\n\t\tname,\n\t\tupdatedAt: now\n\t}).where(eq(organizations.id, organizationId)).returning();\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\treturn organization;\n}\nasync function updateOrganizationSlug(organizationId, slug) {\n\tconst db = getDb();\n\tconst parsedSlug = ClaimableOrganizationSlugSchema.parse(slug);\n\tif (await isOrganizationSlugTaken(parsedSlug, organizationId)) throw new OrganizationSlugTakenError();\n\tconst now = /* @__PURE__ */ new Date();\n\ttry {\n\t\tconst [organization] = await db.update(organizations).set({\n\t\t\tslug: parsedSlug,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(organizations.id, organizationId)).returning();\n\t\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\t\treturn organization;\n\t} catch (error) {\n\t\tif (isOrganizationSlugUniqueViolation(error)) throw new OrganizationSlugTakenError();\n\t\tthrow error;\n\t}\n}\nvar OrganizationSlugTakenError = class extends Error {\n\tconstructor() {\n\t\tsuper(ORGANIZATION_SLUG_TAKEN_MESSAGE);\n\t\tthis.name = \"OrganizationSlugTakenError\";\n\t}\n};\nfunction isOrganizationSlugUniqueViolation(error) {\n\tif (typeof error !== \"object\" || error === null) return false;\n\tif ((\"code\" in error ? String(error.code) : \"\") === \"23505\") return true;\n\treturn (\"message\" in error ? String(error.message) : \"\").includes(\"organizations_slug_unique\");\n}\nasync function resolveNewOrganizationIdentity(name, preferredSlug) {\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Organization name is required\");\n\tconst organizationId = crypto.randomUUID();\n\tconst autoSlug = slugifyOrganizationName(trimmedName);\n\tconst requestedSlug = preferredSlug?.trim() ? normalizeOrganizationSlugInput(trimmedName, preferredSlug) : autoSlug;\n\treturn {\n\t\torganizationId,\n\t\tslug: Boolean(preferredSlug?.trim()) ? await (async () => {\n\t\t\tif (await isOrganizationSlugTaken(requestedSlug)) throw new OrganizationSlugTakenError();\n\t\t\treturn requestedSlug;\n\t\t})() : await resolveAvailableOrganizationSlug(trimmedName, requestedSlug)\n\t};\n}\nasync function createOrganizationForUser(userId, name, preferredSlug, options = {}) {\n\tconst db = getDb();\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Organization name is required\");\n\tconst { organizationId, slug } = options.organizationId && options.slug ? {\n\t\torganizationId: options.organizationId,\n\t\tslug: options.slug\n\t} : await resolveNewOrganizationIdentity(trimmedName, preferredSlug);\n\tconst now = /* @__PURE__ */ new Date();\n\tconst verifiedAt = process.env.NODE_ENV !== \"production\" ? now : null;\n\tconst database = await provisionOrgDatabase(organizationId);\n\tconst redis = await provisionOrgRedis(organizationId);\n\ttry {\n\t\treturn await db.transaction(async (tx) => {\n\t\t\tconst [organization] = await tx.insert(organizations).values({\n\t\t\t\tid: organizationId,\n\t\t\t\tname: trimmedName,\n\t\t\t\tslug,\n\t\t\t\tdbSchema: database.dbSchema,\n\t\t\t\tdbUser: database.dbUser,\n\t\t\t\tdbPasswordCiphertext: database.dbPasswordCiphertext,\n\t\t\t\tredisUrlCiphertext: redis.redisUrlCiphertext || null,\n\t\t\t\thostingAppName: options.hostingAppName ?? null,\n\t\t\t\tstorageBucket: options.storage?.bucket ?? null,\n\t\t\t\tstorageEndpoint: options.storage?.endpoint ?? null,\n\t\t\t\tstorageAccessKeyIdCiphertext: options.storage?.accessKeyIdCiphertext ?? null,\n\t\t\t\tstorageSecretAccessKeyCiphertext: options.storage?.secretAccessKeyCiphertext ?? null,\n\t\t\t\tstorageRegion: options.storage?.region ?? null,\n\t\t\t\tstorageForcePathStyle: options.storage?.forcePathStyle ?? null,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tverifiedAt\n\t\t\t}).returning();\n\t\t\tawait tx.insert(organizationUsers).values({\n\t\t\t\torganizationId,\n\t\t\t\tuserId,\n\t\t\t\trole: \"owner\",\n\t\t\t\tstatus: \"active\",\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t});\n\t\t\tif (!organization) throw new Error(\"Failed to create organization\");\n\t\t\tawait ensureDefaultProjectForUserInTransaction(tx, userId, organizationId);\n\t\t\treturn {\n\t\t\t\torganization,\n\t\t\t\trole: \"owner\"\n\t\t\t};\n\t\t});\n\t} catch (error) {\n\t\tawait deprovisionOrgDatabase(database).catch(() => void 0);\n\t\tawait deprovisionOrgRedis(organizationId).catch(() => void 0);\n\t\tif (isOrganizationSlugUniqueViolation(error)) throw new OrganizationSlugTakenError();\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/queries/project-users/index.ts\nasync function selectUserProjectMembership(userId, projectId) {\n\treturn (await getDb().select().from(projectUsers).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt))).limit(1))[0];\n}\nasync function selectProjectMembers(projectId) {\n\treturn (await getDb().select({\n\t\tid: users.id,\n\t\tprojectId: projectUsers.projectId,\n\t\tname: users.name,\n\t\temail: users.email,\n\t\trole: projectUsers.role,\n\t\torgStatus: organizationUsers.status,\n\t\timage: users.image,\n\t\tcreatedAt: projectUsers.createdAt\n\t}).from(projectUsers).innerJoin(users, eq$1(projectUsers.userId, users.id)).innerJoin(projects, eq$1(projectUsers.projectId, projects.id)).leftJoin(organizationUsers, and$1(eq$1(organizationUsers.organizationId, projects.organizationId), eq$1(organizationUsers.userId, projectUsers.userId), isNull$1(organizationUsers.deletedAt))).where(and$1(eq$1(projectUsers.projectId, projectId), isNull$1(projectUsers.deletedAt)))).map(({ orgStatus, ...row }) => ({\n\t\t...row,\n\t\tstatus: orgStatus === \"invited\" ? \"invited\" : \"active\"\n\t}));\n}\nasync function selectProjectIdsForUser(organizationId, userId) {\n\treturn (await getDb().select({ projectId: projectUsers.projectId }).from(projectUsers).innerJoin(projects, eq$1(projectUsers.projectId, projects.id)).where(and$1(eq$1(projects.organizationId, organizationId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt), isNull$1(projects.deletedAt)))).map((row) => row.projectId);\n}\nasync function upsertProjectMember(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [existing] = await db.select().from(projectUsers).where(and$1(eq$1(projectUsers.projectId, input.projectId), eq$1(projectUsers.userId, input.userId))).limit(1);\n\tif (!existing) {\n\t\tawait db.insert(projectUsers).values({\n\t\t\tprojectId: input.projectId,\n\t\t\tuserId: input.userId,\n\t\t\trole: input.role,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn;\n\t}\n\tawait db.update(projectUsers).set({\n\t\trole: input.role,\n\t\tstatus: \"active\",\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t}).where(and$1(eq$1(projectUsers.projectId, input.projectId), eq$1(projectUsers.userId, input.userId)));\n}\nasync function updateProjectMemberRole(projectId, userId, role) {\n\tif (!await selectUserProjectMembership(userId, projectId)) throw new ProjectMemberNotFoundError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().update(projectUsers).set({\n\t\trole,\n\t\tupdatedAt: now\n\t}).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt)));\n\tconst [member] = (await selectProjectMembers(projectId)).filter((row) => row.id === userId);\n\tif (!member) throw new ProjectMemberNotFoundError();\n\treturn member;\n}\nasync function removeProjectMember(projectId, userId) {\n\tif (!await selectUserProjectMembership(userId, projectId)) throw new ProjectMemberNotFoundError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().update(projectUsers).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt)));\n}\nasync function backfillProjectUsers() {\n\tconst activeProjects = await getDb().select({\n\t\tid: projects.id,\n\t\tcreatedByUserId: projects.createdByUserId\n\t}).from(projects).where(isNull$1(projects.deletedAt));\n\tfor (const project of activeProjects) if (project.createdByUserId) await upsertProjectMember({\n\t\tprojectId: project.id,\n\t\tuserId: project.createdByUserId,\n\t\trole: \"admin\"\n\t});\n}\nasync function inviteProjectMembers(input) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst results = [];\n\tconst db = getDb();\n\tfor (const rawEmail of input.emails) {\n\t\tconst normalized = normalizeUserEmail(rawEmail);\n\t\tif (seen.has(normalized)) continue;\n\t\tseen.add(normalized);\n\t\tif (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(normalized)) {\n\t\t\tresults.push({\n\t\t\t\temail: rawEmail.trim(),\n\t\t\t\tstatus: \"invalid\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst [orgUser] = await db.select({ userId: organizationUsers.userId }).from(organizationUsers).innerJoin(users, eq$1(organizationUsers.userId, users.id)).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(users.email, normalized), inArray$1(organizationUsers.status, [\"active\", \"invited\"]), isNull$1(organizationUsers.deletedAt))).limit(1);\n\t\tif (!orgUser) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"not_org_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (await selectUserProjectMembership(orgUser.userId, input.projectId)) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"already_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tawait upsertProjectMember({\n\t\t\tprojectId: input.projectId,\n\t\t\tuserId: orgUser.userId,\n\t\t\trole: input.role\n\t\t});\n\t\tresults.push({\n\t\t\temail: normalized,\n\t\t\tstatus: \"added\"\n\t\t});\n\t}\n\treturn results;\n}\nvar ProjectMemberNotFoundError = class extends Error {\n\tconstructor(message = \"Project member not found\") {\n\t\tsuper(message);\n\t\tthis.name = \"ProjectMemberNotFoundError\";\n\t}\n};\n//#endregion\n//#region src/queries/projects/index.ts\nasync function selectProjectById(projectId) {\n\treturn (await getDb().select().from(projects).where(eq(projects.id, projectId)).limit(1))[0];\n}\nasync function selectProjectsByOrganizationId(organizationId, options) {\n\tconst db = getDb();\n\tconst grantedIds = options?.grantedProjectIds;\n\tconst conditions = [eq(projects.organizationId, organizationId), isNull(projects.deletedAt)];\n\tif (grantedIds !== void 0) {\n\t\tif (grantedIds.length === 0) return [];\n\t\tconditions.push(inArray(projects.id, grantedIds));\n\t}\n\treturn db.select().from(projects).where(and(...conditions)).orderBy(asc(projects.createdAt));\n}\nasync function selectProjectForOrganization(organizationId, projectId) {\n\treturn (await getDb().select().from(projects).where(and(eq(projects.id, projectId), eq(projects.organizationId, organizationId), isNull(projects.deletedAt))).limit(1))[0];\n}\nasync function selectProjectForOrganizationBySlug(organizationId, slug) {\n\tconst db = getDb();\n\tconst normalizedSlug = slug.trim().toLowerCase();\n\treturn (await db.select().from(projects).where(and(eq(projects.organizationId, organizationId), eq(projects.slug, normalizedSlug), isNull(projects.deletedAt))).limit(1))[0];\n}\nasync function createProjectForOrganization(organizationId, name, description, createdByUserId) {\n\tconst db = getDb();\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Project name is required\");\n\tconst trimmedDescription = description === void 0 || description === null ? null : description.trim() || null;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst projectId = crypto.randomUUID();\n\tconst slug = await resolveAvailableProjectSlug(db, organizationId, trimmedName);\n\tconst [project] = await db.insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: trimmedName,\n\t\tslug,\n\t\tdescription: trimmedDescription,\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tcreatedByUserId: createdByUserId ?? null,\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (!project) throw new Error(\"Failed to create project\");\n\tif (createdByUserId) await upsertProjectMember({\n\t\tprojectId: project.id,\n\t\tuserId: createdByUserId,\n\t\trole: \"admin\"\n\t});\n\treturn project;\n}\nasync function updateProjectForOrganization(organizationId, projectId, patch) {\n\tconst existing = await selectProjectForOrganization(organizationId, projectId);\n\tif (!existing) return;\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (patch.name !== void 0) {\n\t\tconst trimmedName = patch.name.trim();\n\t\tif (!trimmedName) throw new Error(\"Project name is required\");\n\t\tupdates.name = trimmedName;\n\t}\n\tif (patch.description !== void 0) updates.description = patch.description.trim() || null;\n\tconst db = getDb();\n\tif (patch.slug !== void 0) {\n\t\tconst parsedSlug = ProjectSlugSchema.parse(patch.slug.trim().toLowerCase());\n\t\tif (parsedSlug !== existing.slug) {\n\t\t\tif (await isProjectSlugTaken(db, organizationId, parsedSlug, projectId)) throw new ProjectSlugTakenError();\n\t\t\tupdates.slug = parsedSlug;\n\t\t}\n\t}\n\ttry {\n\t\treturn (await db.update(projects).set(updates).where(eq(projects.id, projectId)).returning())[0];\n\t} catch (error) {\n\t\tif (isProjectSlugUniqueViolation(error)) throw new ProjectSlugTakenError();\n\t\tthrow error;\n\t}\n}\nasync function updateProjectSettings(organizationId, projectId, patch) {\n\tif (!await selectProjectForOrganization(organizationId, projectId)) return;\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (patch.description !== void 0) updates.description = patch.description.trim() || null;\n\tif (patch.defaultMemberRole !== void 0) updates.defaultMemberRole = patch.defaultMemberRole;\n\tif (patch.invitePermission !== void 0) updates.invitePermission = patch.invitePermission;\n\treturn (await getDb().update(projects).set(updates).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function deleteProjectForOrganization(organizationId, projectId) {\n\tif (!await selectProjectForOrganization(organizationId, projectId)) return;\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await getDb().update(projects).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function updateProjectActive(projectId, input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"active\",\n\t\tbaseUrl: input.baseUrl,\n\t\truntimeId: input.runtimeId,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function updateProjectFailed(projectId, lastError) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"failed\",\n\t\tlastError,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\n//#endregion\n//#region src/standalone/default-org.ts\nconst DEFAULT_STANDALONE_ORGANIZATION_ID = \"default\";\nconst DEFAULT_STANDALONE_ORGANIZATION_SLUG = \"default\";\nconst DEFAULT_STANDALONE_ORGANIZATION_NAME = \"Default Organization\";\nconst DEFAULT_STANDALONE_PROJECT_NAME = \"Default Project\";\nconst DEFAULT_STANDALONE_PROJECT_SLUG = \"default\";\nfunction isStandaloneMode(env = process.env) {\n\treturn env.KEYSTROKE_APP_MODE === \"standalone\" || env.KEYSTROKE_STANDALONE === \"1\";\n}\nasync function ensureDefaultOrganization() {\n\tconst organizationId = DEFAULT_STANDALONE_ORGANIZATION_ID;\n\tif (await selectOrganizationById(organizationId)) return { organizationId };\n\tconst now = /* @__PURE__ */ new Date();\n\tconst provisioned = await provisionOrgDatabase(organizationId);\n\tconst redis = await provisionOrgRedis(organizationId);\n\tif (isSqliteDialect()) await getSqliteDb().insert(organizationsSqlite).values({\n\t\tid: organizationId,\n\t\tname: DEFAULT_STANDALONE_ORGANIZATION_NAME,\n\t\tslug: DEFAULT_STANDALONE_ORGANIZATION_SLUG,\n\t\tdbSchema: provisioned.dbSchema,\n\t\tdbUser: provisioned.dbUser,\n\t\tdbPasswordCiphertext: provisioned.dbPasswordCiphertext,\n\t\tredisUrlCiphertext: redis.redisUrlCiphertext || null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\n\telse await getDb().insert(organizations).values({\n\t\tid: organizationId,\n\t\tname: DEFAULT_STANDALONE_ORGANIZATION_NAME,\n\t\tslug: DEFAULT_STANDALONE_ORGANIZATION_SLUG,\n\t\tdbSchema: provisioned.dbSchema,\n\t\tdbUser: provisioned.dbUser,\n\t\tdbPasswordCiphertext: provisioned.dbPasswordCiphertext,\n\t\tredisUrlCiphertext: redis.redisUrlCiphertext || null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\n\treturn { organizationId };\n}\nasync function ensureDefaultProject(organizationId) {\n\tconst projectId = DEFAULT_PROJECT_ID;\n\tif (await selectProjectForOrganization(organizationId, projectId)) return { projectId };\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) await getSqliteDb().insert(projectsSqlite).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: DEFAULT_STANDALONE_PROJECT_NAME,\n\t\tslug: DEFAULT_STANDALONE_PROJECT_SLUG,\n\t\tdescription: \"Default standalone project\",\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\telse await getDb().insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: DEFAULT_STANDALONE_PROJECT_NAME,\n\t\tslug: DEFAULT_STANDALONE_PROJECT_SLUG,\n\t\tdescription: \"Default standalone project\",\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn { projectId };\n}\nasync function ensureDefaultOrganizationAndProject() {\n\tconst { organizationId } = await ensureDefaultOrganization();\n\tconst { projectId } = await ensureDefaultProject(organizationId);\n\treturn {\n\t\torganizationId,\n\t\tprojectId\n\t};\n}\nasync function runWithStandaloneScope(fn) {\n\tconst { organizationId, projectId } = await ensureDefaultOrganizationAndProject();\n\treturn runWithOrganizationScope(organizationId, () => runWithTenantScope(organizationId, () => runWithProjectScope(projectId, fn)));\n}\n//#endregion\n//#region src/queries/api-keys/index.ts\nasync function selectApiKeyByConfigName(configId, name) {\n\treturn (await getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.name, name))).limit(1))[0];\n}\nasync function selectApiKeyById(id) {\n\treturn (await getDb().select().from(authApiKeys).where(eq$1(authApiKeys.id, id)).limit(1))[0];\n}\nasync function selectApiKeyByConfigAndHash(configId, keyHash) {\n\treturn (await getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.key, keyHash))).limit(1))[0];\n}\nasync function listApiKeysByConfigId(configId) {\n\treturn getDb().select().from(authApiKeys).where(eq$1(authApiKeys.configId, configId));\n}\nasync function listApiKeysByConfigReferenceId(configId, referenceId) {\n\treturn getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.referenceId, referenceId)));\n}\nasync function insertApiKey(values) {\n\tif (isSqliteDialect()) {\n\t\tawait getSqliteDb().insert(authApiKeysSqlite).values(values);\n\t\treturn;\n\t}\n\tawait getDb().insert(authApiKeys).values(values);\n}\nasync function deleteApiKeyById(id) {\n\tawait getDb().delete(authApiKeys).where(eq$1(authApiKeys.id, id));\n}\n//#endregion\n//#region src/queries/members/errors.ts\nvar OrganizationMemberMutationError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationMemberMutationError\";\n\t\tthis.code = code;\n\t}\n};\nvar CannotModifyOwnerError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"Organization owners cannot be modified this way\") {\n\t\tsuper(\"cannot_modify_owner\", message);\n\t}\n};\nvar LastOwnerError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"The organization must have at least one owner\") {\n\t\tsuper(\"last_owner\", message);\n\t}\n};\nvar OrganizationMemberNotFoundError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"Member not found\") {\n\t\tsuper(\"member_not_found\", message);\n\t}\n};\n//#endregion\n//#region src/queries/members/index.ts\nconst INVITATION_TTL_MS = 336 * 60 * 60 * 1e3;\nasync function selectOrganizationMembers(organizationId) {\n\treturn getDb().select({\n\t\tid: users.id,\n\t\tname: users.name,\n\t\temail: users.email,\n\t\trole: organizationUsers.role,\n\t\tstatus: organizationUsers.status,\n\t\timage: users.image,\n\t\tcreatedAt: organizationUsers.createdAt\n\t}).from(organizationUsers).innerJoin(users, eq$1(organizationUsers.userId, users.id)).where(and$1(eq$1(organizationUsers.organizationId, organizationId), isNull$1(organizationUsers.deletedAt)));\n}\nasync function selectOrganizationMembership(organizationId, userId) {\n\treturn (await getDb().select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt))).limit(1))[0];\n}\nasync function selectPendingInvitation(organizationId, userId) {\n\treturn (await getDb().select().from(organizationInvitations).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\"))).limit(1))[0];\n}\nfunction isValidInviteEmail(email) {\n\treturn /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n}\nasync function inviteOrganizationMembers(input) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst results = [];\n\tfor (const rawEmail of input.emails) {\n\t\tconst normalized = normalizeUserEmail(rawEmail);\n\t\tif (seen.has(normalized)) continue;\n\t\tseen.add(normalized);\n\t\tif (!isValidInviteEmail(normalized)) {\n\t\t\tresults.push({\n\t\t\t\temail: rawEmail.trim(),\n\t\t\t\tstatus: \"invalid\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst user = await findOrCreateUserByEmail(normalized);\n\t\tif ((await selectOrganizationMembership(input.organizationId, user.id))?.status === \"active\") {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"already_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst pending = await selectPendingInvitation(input.organizationId, user.id);\n\t\tif (pending) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tinvitationId: pending.id\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tconst db = getDb();\n\t\tconst invitationId = crypto.randomUUID();\n\t\ttry {\n\t\t\tawait db.transaction(async (tx) => {\n\t\t\t\tawait tx.insert(organizationInvitations).values({\n\t\t\t\t\tid: invitationId,\n\t\t\t\t\torganizationId: input.organizationId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\temail: normalized,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tinvitedByUserId: input.invitedByUserId,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\texpiresAt: new Date(now.getTime() + INVITATION_TTL_MS)\n\t\t\t\t});\n\t\t\t\tconst [existing] = await tx.select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(organizationUsers.userId, user.id))).limit(1);\n\t\t\t\tif (!existing) await tx.insert(organizationUsers).values({\n\t\t\t\t\torganizationId: input.organizationId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"invited\",\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now\n\t\t\t\t});\n\t\t\t\telse await tx.update(organizationUsers).set({\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"invited\",\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\tdeletedAt: null\n\t\t\t\t}).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(organizationUsers.userId, user.id)));\n\t\t\t});\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"sent\",\n\t\t\t\tinvitationId\n\t\t\t});\n\t\t} catch {\n\t\t\tconst raced = await selectPendingInvitation(input.organizationId, user.id);\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: raced ? \"pending\" : \"sent\",\n\t\t\t\tinvitationId: raced?.id ?? invitationId\n\t\t\t});\n\t\t}\n\t}\n\treturn results;\n}\nfunction isEditableOrganizationMemberStatus(status) {\n\treturn status === \"active\" || status === \"invited\";\n}\nasync function updateOrganizationMemberRole(organizationId, userId, role) {\n\tconst membership = await selectOrganizationMembership(organizationId, userId);\n\tif (!membership || !isEditableOrganizationMemberStatus(membership.status)) throw new OrganizationMemberNotFoundError();\n\tif (membership.role === \"owner\") throw new CannotModifyOwnerError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tawait tx.update(organizationUsers).set({\n\t\t\trole,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t\tif (membership.status === \"invited\") await tx.update(organizationInvitations).set({\n\t\t\trole,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\")));\n\t});\n\tconst [member] = await selectOrganizationMembers(organizationId).then((rows) => rows.filter((row) => row.id === userId));\n\tif (!member) throw new OrganizationMemberNotFoundError();\n\treturn member;\n}\nasync function removeOrganizationMember(organizationId, userId) {\n\tconst membership = await selectOrganizationMembership(organizationId, userId);\n\tif (!membership) throw new OrganizationMemberNotFoundError();\n\tif (membership.role === \"owner\" && membership.status === \"active\") throw new CannotModifyOwnerError(\"Organization owners cannot be removed\");\n\tif (membership.status === \"suspended\") return;\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tif (membership.status === \"invited\") await tx.update(organizationInvitations).set({\n\t\t\tstatus: \"declined\",\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\")));\n\t\tawait tx.update(organizationUsers).set({\n\t\t\tstatus: \"suspended\",\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t});\n}\n//#endregion\n//#region src/queries/invitations/index.ts\nvar OrganizationInvitationNotFoundError = class extends Error {\n\tconstructor(message = \"Invitation not found\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationNotFoundError\";\n\t}\n};\nvar OrganizationInvitationForbiddenError = class extends Error {\n\tconstructor(message = \"Forbidden\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationForbiddenError\";\n\t}\n};\nvar OrganizationInvitationExpiredError = class extends Error {\n\tconstructor(message = \"Invitation has expired\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationExpiredError\";\n\t}\n};\nasync function selectInvitationById(invitationId) {\n\treturn (await getDb().select().from(organizationInvitations).where(eq$1(organizationInvitations.id, invitationId)).limit(1))[0];\n}\nfunction isInvitationExpired(invitation, now = /* @__PURE__ */ new Date()) {\n\treturn invitation.expiresAt !== null && invitation.expiresAt.getTime() <= now.getTime();\n}\nasync function selectPendingInvitationsForUser(userId) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn db.select({\n\t\tid: organizationInvitations.id,\n\t\torganizationName: organizations.name,\n\t\torganizationSlug: organizations.slug,\n\t\trole: organizationInvitations.role,\n\t\tinvitedByName: users.name,\n\t\tinvitedByEmail: users.email\n\t}).from(organizationInvitations).innerJoin(organizations, eq$1(organizationInvitations.organizationId, organizations.id)).innerJoin(users, eq$1(organizationInvitations.invitedByUserId, users.id)).where(and$1(eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\"), or(isNull$1(organizationInvitations.expiresAt), gt(organizationInvitations.expiresAt, now))));\n}\nasync function acceptInvitation(invitationId, userId) {\n\tconst invitation = await selectInvitationById(invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw new OrganizationInvitationNotFoundError();\n\tif (invitation.userId !== userId) throw new OrganizationInvitationForbiddenError();\n\tif (isInvitationExpired(invitation)) throw new OrganizationInvitationExpiredError();\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait db.transaction(async (tx) => {\n\t\tconst [existing] = await tx.select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId))).limit(1);\n\t\tif (!existing) await tx.insert(organizationUsers).values({\n\t\t\torganizationId: invitation.organizationId,\n\t\t\tuserId,\n\t\t\trole: invitation.role,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\telse await tx.update(organizationUsers).set({\n\t\t\trole: existing.role === \"owner\" ? \"owner\" : invitation.role,\n\t\t\tstatus: \"active\",\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId)));\n\t\tawait ensureDefaultProjectForUserInTransaction(tx, userId, invitation.organizationId);\n\t\tawait tx.update(organizationInvitations).set({\n\t\t\tstatus: \"accepted\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(organizationInvitations.id, invitationId));\n\t});\n\tconst membership = await selectUserOrganizationMembership(userId, invitation.organizationId);\n\tif (!membership) throw new OrganizationMemberNotFoundError(\"Failed to load membership after accept\");\n\treturn membership;\n}\nasync function declineInvitation(invitationId, userId) {\n\tconst invitation = await selectInvitationById(invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw new OrganizationInvitationNotFoundError();\n\tif (invitation.userId !== userId) throw new OrganizationInvitationForbiddenError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tawait tx.update(organizationUsers).set({\n\t\t\tstatus: \"rejected\",\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t\tawait tx.update(organizationInvitations).set({\n\t\t\tstatus: \"declined\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(organizationInvitations.id, invitationId));\n\t});\n}\n//#endregion\n//#region src/queries/organization-users/index.ts\nasync function selectOrganizationUsersByUserId(userId) {\n\treturn getDb().select().from(organizationUsers).where(eq(organizationUsers.userId, userId));\n}\n//#endregion\n//#region src/queries/project-artifacts/complete-promote.ts\n/** Mark artifact ready and stage it as pending — does not flip activeArtifactId or sync registry. */\nasync function completeProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\t\tstatus: \"ready\",\n\t\t\tmanifestJson: input.manifestJson ?? null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"pending\"))).returning();\n\t\tif (!artifact) throw new Error(\"Artifact not found or already completed\");\n\t\tconst [project] = await db.update(projects).set({\n\t\t\tpendingArtifactId: artifact.id,\n\t\t\tstatus: \"starting\",\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject\n\t\t};\n\t}\n\treturn db.transaction(async (tx) => {\n\t\tconst [artifact] = await tx.update(projectArtifacts).set({\n\t\t\tstatus: \"ready\",\n\t\t\tmanifestJson: input.manifestJson ?? null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"pending\"))).returning();\n\t\tif (!artifact) throw new Error(\"Artifact not found or already completed\");\n\t\tconst [project] = await tx.update(projects).set({\n\t\t\tpendingArtifactId: artifact.id,\n\t\t\tstatus: \"starting\",\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject\n\t\t};\n\t});\n}\n/** Cut over live deploy to a staged artifact after the new runtime is healthy. */\nasync function promoteProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tconst [project] = await db.select().from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\tif (project.pendingArtifactId !== input.artifactId) throw new Error(\"Artifact is not the pending deploy for this project\");\n\t\tconst [artifact] = await db.select().from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"ready\"))).limit(1);\n\t\tif (!artifact) throw new Error(\"Pending artifact not found or not ready\");\n\t\tconst [updatedProject] = await db.update(projects).set({\n\t\t\tactiveArtifactId: artifact.id,\n\t\t\tpendingArtifactId: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!updatedProject) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject: updatedProject\n\t\t};\n\t}\n\treturn db.transaction(async (tx) => {\n\t\tconst [project] = await tx.select().from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\tif (project.pendingArtifactId !== input.artifactId) throw new Error(\"Artifact is not the pending deploy for this project\");\n\t\tconst [artifact] = await tx.select().from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"ready\"))).limit(1);\n\t\tif (!artifact) throw new Error(\"Pending artifact not found or not ready\");\n\t\tconst [updatedProject] = await tx.update(projects).set({\n\t\t\tactiveArtifactId: artifact.id,\n\t\t\tpendingArtifactId: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!updatedProject) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject: updatedProject\n\t\t};\n\t});\n}\nasync function updateProjectArtifactManifest(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\tmanifestJson: input.manifestJson,\n\t\tupdatedAt: now\n\t}).where(eq(projectArtifacts.id, input.artifactId)).returning();\n\tif (!artifact) throw new Error(\"Artifact not found\");\n\treturn artifact;\n}\n/** Attach a deploy's source manifest (file tree) to its artifact. */\nasync function updateProjectArtifactSourceManifest(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\tsourceManifestJson: input.sourceManifestJson,\n\t\tupdatedAt: now\n\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).returning();\n\tif (!artifact) throw new Error(\"Artifact not found\");\n\treturn artifact;\n}\n//#endregion\n//#region src/queries/project-artifacts/last-deployment.ts\n/** Latest ready artifact timestamp per project for an organization. */\nasync function selectLastDeploymentAtByProject(organizationId) {\n\tconst rows = await getDb().select({\n\t\tprojectId: projectArtifacts.projectId,\n\t\tlastDeploymentAt: max(projectArtifacts.updatedAt)\n\t}).from(projectArtifacts).innerJoin(projects, eq(projects.id, projectArtifacts.projectId)).where(and(eq(projects.organizationId, organizationId), isNull(projects.deletedAt), eq(projectArtifacts.status, \"ready\"))).groupBy(projectArtifacts.projectId);\n\tconst result = {};\n\tfor (const row of rows) if (row.lastDeploymentAt) result[row.projectId] = row.lastDeploymentAt;\n\treturn result;\n}\n//#endregion\n//#region src/queries/project-artifacts/deployments.ts\n/** Ready artifact deploy history for a project, newest first. */\nasync function selectProjectDeployments(projectId) {\n\treturn (await getDb().select({\n\t\tid: projectArtifacts.id,\n\t\tprojectId: projectArtifacts.projectId,\n\t\tversion: projectArtifacts.version,\n\t\tcreatedAt: projectArtifacts.createdAt,\n\t\tactiveArtifactId: projects.activeArtifactId,\n\t\tdeployedByName: users.name,\n\t\tdeployedByEmail: users.email,\n\t\tdeployedByAvatarUrl: users.image\n\t}).from(projectArtifacts).innerJoin(projects, eq(projects.id, projectArtifacts.projectId)).leftJoin(users, eq(users.id, projectArtifacts.createdByUserId)).where(and(eq(projectArtifacts.projectId, projectId), eq(projectArtifacts.status, \"ready\"))).orderBy(desc(projectArtifacts.createdAt))).map((row) => ({\n\t\tid: row.id,\n\t\tprojectId: row.projectId,\n\t\tversion: row.version,\n\t\tcreatedAt: row.createdAt,\n\t\tactive: row.activeArtifactId === row.id,\n\t\tdeployedByName: row.deployedByName,\n\t\tdeployedByEmail: row.deployedByEmail,\n\t\tdeployedByAvatarUrl: row.deployedByAvatarUrl\n\t}));\n}\n//#endregion\n//#region src/queries/project-artifacts/index.ts\nasync function insertProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [versionRow] = await db.select({ maxVersion: max(projectArtifacts.version) }).from(projectArtifacts).where(eq(projectArtifacts.projectId, input.projectId));\n\tconst version = (versionRow?.maxVersion ?? 0) + 1;\n\tconst [row] = await db.insert(projectArtifacts).values({\n\t\tid: input.id,\n\t\tprojectId: input.projectId,\n\t\tstorageKey: input.storageKey,\n\t\tversion,\n\t\tcreatedByUserId: input.createdByUserId ?? null,\n\t\tstatus: \"pending\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (!row) throw new Error(\"Failed to create project artifact\");\n\treturn row;\n}\nasync function selectProjectArtifactById(artifactId) {\n\treturn (await getDb().select().from(projectArtifacts).where(eq(projectArtifacts.id, artifactId)).limit(1))[0];\n}\nasync function selectProjectArtifactForProject(artifactId, projectId) {\n\treturn (await getDb().select().from(projectArtifacts).where(and(eq(projectArtifacts.id, artifactId), eq(projectArtifacts.projectId, projectId))).limit(1))[0];\n}\nasync function selectActiveProjectArtifactForProject(projectId) {\n\tconst activeArtifactId = (await getDb().select({ activeArtifactId: projects.activeArtifactId }).from(projects).where(eq(projects.id, projectId)).limit(1))[0]?.activeArtifactId;\n\tif (!activeArtifactId) return;\n\treturn selectProjectArtifactForProject(activeArtifactId, projectId);\n}\nasync function selectActiveArtifactManifestForProject(projectId) {\n\treturn (await getDb().select({ manifestJson: projectArtifacts.manifestJson }).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(eq(projects.id, projectId)).limit(1))[0]?.manifestJson ?? void 0;\n}\n/** Source manifest (file tree) for the project's currently active deploy. */\nasync function selectActiveArtifactSourceManifestForProject(projectId) {\n\treturn (await getDb().select({\n\t\tartifactId: projectArtifacts.id,\n\t\tsourceManifestJson: projectArtifacts.sourceManifestJson\n\t}).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(eq(projects.id, projectId)).limit(1))[0];\n}\n/** Runtime and source manifests for active deploys in an organization. */\nasync function selectActiveArtifactManifestsByOrganizationId(organizationId) {\n\treturn getDb().select({\n\t\tprojectId: projects.id,\n\t\tprojectUpdatedAt: projects.updatedAt,\n\t\tartifactId: projectArtifacts.id,\n\t\tartifactUpdatedAt: projectArtifacts.updatedAt,\n\t\tmanifestJson: projectArtifacts.manifestJson,\n\t\tsourceManifestJson: projectArtifacts.sourceManifestJson\n\t}).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(and(eq(projects.organizationId, organizationId), isNull(projects.deletedAt)));\n}\n//#endregion\n//#region src/api-keys/constants.ts\nconst WEBHOOK_API_KEY_CONFIG_ID = \"webhook\";\nconst ORG_PLATFORM_API_KEY_CONFIG_ID = \"org-platform\";\nfunction generateApiKeySecret(prefix = \"wh_\") {\n\treturn `${prefix}${randomBytes(32).toString(\"base64url\")}`;\n}\nfunction apiKeyStart(secret, length = 8) {\n\treturn secret.slice(0, length);\n}\nfunction encryptApiKeySecret(secret) {\n\treturn encryptCredentialPayload$1(secret);\n}\nfunction decryptApiKeySecret(ciphertext) {\n\treturn decryptCredentialPayload$1(ciphertext);\n}\nfunction hashApiKeySecret(secret) {\n\treturn createHash(\"sha256\").update(secret).digest(\"base64\");\n}\nfunction verifyApiKeySecret(secret, storedHash) {\n\tconst actual = Buffer.from(hashApiKeySecret(secret));\n\tconst expected = Buffer.from(storedHash);\n\tif (actual.length !== expected.length) return false;\n\treturn timingSafeEqual(actual, expected);\n}\n//#endregion\n//#region src/api-keys/metadata.ts\nfunction parseWebhookApiKeyMetadata(metadata) {\n\tif (!metadata) return null;\n\ttry {\n\t\tconst value = JSON.parse(metadata);\n\t\tif (value.kind !== \"trigger-webhook\" || typeof value.route !== \"string\" || typeof value.projectId !== \"string\") return null;\n\t\tconst rawSlugs = value.attachmentSlugs ?? value.attachmentKeys;\n\t\tconst attachmentSlugs = Array.isArray(rawSlugs) ? rawSlugs.filter((slug) => typeof slug === \"string\") : [];\n\t\treturn {\n\t\t\tkind: \"trigger-webhook\",\n\t\t\tprojectId: value.projectId,\n\t\t\troute: value.route,\n\t\t\tattachmentSlugs\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction serializeWebhookApiKeyMetadata(metadata) {\n\treturn JSON.stringify(metadata);\n}\n//#endregion\n//#region src/api-keys/list.ts\nasync function listWebhookApiKeys() {\n\tconst rows = await listApiKeysByConfigId(WEBHOOK_API_KEY_CONFIG_ID);\n\tconst views = [];\n\tfor (const row of rows) {\n\t\tconst parsed = parseWebhookApiKeyMetadata(row.metadata);\n\t\tif (!parsed || !row.keyCiphertext) continue;\n\t\tviews.push({\n\t\t\tid: row.id,\n\t\t\tprojectId: parsed.projectId,\n\t\t\troute: parsed.route,\n\t\t\tname: row.name,\n\t\t\tstart: row.start,\n\t\t\tprefix: row.prefix,\n\t\t\ttoken: decryptApiKeySecret(row.keyCiphertext),\n\t\t\tattachmentSlugs: parsed.attachmentSlugs,\n\t\t\tcreatedAt: row.createdAt,\n\t\t\tupdatedAt: row.updatedAt\n\t\t});\n\t}\n\treturn views;\n}\nasync function listWebhookApiKeysForProject(projectId) {\n\treturn (await listWebhookApiKeys()).filter((key) => key.projectId === projectId);\n}\n//#endregion\n//#region src/api-keys/ensure.ts\nfunction webhookEndpointSuffix(route) {\n\treturn route.startsWith(\"/triggers/\") ? route.slice(10) : route;\n}\nfunction webhookApiKeyName(projectId, route) {\n\treturn `${projectId}:${webhookEndpointSuffix(route)}`;\n}\nasync function ensureWebhookApiKeys(projectId, routes, referenceId) {\n\tconst created = [];\n\tconst existing = [];\n\tfor (const { route, attachmentSlugs } of routes) {\n\t\tconst name = webhookApiKeyName(projectId, route);\n\t\tif (await selectApiKeyByConfigName(\"webhook\", name)) {\n\t\t\texisting.push(route);\n\t\t\tcontinue;\n\t\t}\n\t\tconst secret = generateApiKeySecret();\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tconst metadata = {\n\t\t\tkind: \"trigger-webhook\",\n\t\t\tprojectId,\n\t\t\troute,\n\t\t\tattachmentSlugs\n\t\t};\n\t\tawait insertApiKey({\n\t\t\tid: crypto.randomUUID(),\n\t\t\tconfigId: WEBHOOK_API_KEY_CONFIG_ID,\n\t\t\tname,\n\t\t\tstart: apiKeyStart(secret),\n\t\t\tprefix: \"wh_\",\n\t\t\tkey: hashApiKeySecret(secret),\n\t\t\tkeyCiphertext: encryptApiKeySecret(secret),\n\t\t\treferenceId,\n\t\t\tmetadata: serializeWebhookApiKeyMetadata(metadata),\n\t\t\tpermissions: JSON.stringify({ triggers: [\"invoke\"] }),\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\tcreated.push({\n\t\t\troute,\n\t\t\ttoken: secret\n\t\t});\n\t}\n\treturn {\n\t\tcreated,\n\t\texisting\n\t};\n}\n/** Idempotently ensures a webhook API key exists and returns the plaintext token. */\nasync function ensureWebhookApiKeyForRoute(projectId, route, attachmentSlugs) {\n\tconst created = (await ensureWebhookApiKeys(projectId, [{\n\t\troute,\n\t\tattachmentSlugs\n\t}], projectId)).created.find((entry) => entry.route === route);\n\tif (created) return created.token;\n\tconst existing = (await listWebhookApiKeysForProject(projectId)).find((entry) => entry.route === route);\n\tif (!existing?.token) throw new Error(`Webhook API key not found for route ${route}`);\n\treturn existing.token;\n}\n//#endregion\n//#region src/api-keys/verify.ts\nasync function verifyWebhookApiKeyForRoute(projectId, route, secret) {\n\tconst row = await selectApiKeyByConfigName(WEBHOOK_API_KEY_CONFIG_ID, webhookApiKeyName(projectId, route));\n\tif (!row) return false;\n\treturn verifyApiKeySecret(secret, row.key);\n}\n//#endregion\n//#region src/api-keys/org-platform-metadata.ts\nfunction parseOrgPlatformApiKeyMetadata(metadata) {\n\tif (!metadata) return null;\n\ttry {\n\t\tconst value = JSON.parse(metadata);\n\t\tif (value.kind !== \"org-platform\" || typeof value.organizationId !== \"string\" || typeof value.createdByUserId !== \"string\" || typeof value.keyPreview !== \"string\") return null;\n\t\treturn {\n\t\t\tkind: \"org-platform\",\n\t\t\torganizationId: value.organizationId,\n\t\t\tcreatedByUserId: value.createdByUserId,\n\t\t\tkeyPreview: value.keyPreview\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction serializeOrgPlatformApiKeyMetadata(metadata) {\n\treturn JSON.stringify(metadata);\n}\n//#endregion\n//#region src/api-keys/org-platform.ts\nvar OrgPlatformApiKeyNotFoundError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"API key not found\");\n\t\tthis.name = \"OrgPlatformApiKeyNotFoundError\";\n\t}\n};\nfunction keyPreviewFromSecret(secret) {\n\treturn `******${secret.slice(-4)}`;\n}\nfunction parseOrgPlatformRow(row) {\n\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\tif (!metadata || row.name == null) return null;\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tkeyPreview: metadata.keyPreview,\n\t\tcreatedAt: row.createdAt,\n\t\tcreatedByUserId: metadata.createdByUserId\n\t};\n}\nfunction isActiveApiKey(row) {\n\tif (row.enabled === false) return false;\n\tif (row.expiresAt && row.expiresAt.getTime() <= Date.now()) return false;\n\treturn true;\n}\nasync function listOrgPlatformApiKeysForUser(organizationId, userId) {\n\tconst rows = await listApiKeysByConfigReferenceId(ORG_PLATFORM_API_KEY_CONFIG_ID, userId);\n\tconst records = [];\n\tfor (const row of rows) {\n\t\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\t\tif (!metadata || metadata.organizationId !== organizationId || metadata.createdByUserId !== userId) continue;\n\t\tconst record = parseOrgPlatformRow(row);\n\t\tif (record) records.push(record);\n\t}\n\treturn records;\n}\nasync function listOrgPlatformApiKeysForOrganization(organizationId) {\n\tconst rows = await listApiKeysByConfigId(ORG_PLATFORM_API_KEY_CONFIG_ID);\n\tconst records = [];\n\tfor (const row of rows) {\n\t\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\t\tif (!metadata || metadata.organizationId !== organizationId) continue;\n\t\tconst record = parseOrgPlatformRow(row);\n\t\tif (record) records.push(record);\n\t}\n\treturn records;\n}\nasync function createOrgPlatformApiKey(input) {\n\tconst secret = generateApiKeySecret(\"sk_\");\n\tconst now = /* @__PURE__ */ new Date();\n\tconst metadata = serializeOrgPlatformApiKeyMetadata({\n\t\tkind: \"org-platform\",\n\t\torganizationId: input.organizationId,\n\t\tcreatedByUserId: input.userId,\n\t\tkeyPreview: keyPreviewFromSecret(secret)\n\t});\n\tconst record = {\n\t\tid: crypto.randomUUID(),\n\t\tname: input.name,\n\t\tkeyPreview: keyPreviewFromSecret(secret),\n\t\tcreatedAt: now,\n\t\tcreatedByUserId: input.userId,\n\t\tsecret\n\t};\n\tawait insertApiKey({\n\t\tid: record.id,\n\t\tconfigId: ORG_PLATFORM_API_KEY_CONFIG_ID,\n\t\tname: input.name,\n\t\tstart: apiKeyStart(secret),\n\t\tprefix: \"sk_\",\n\t\tkey: hashApiKeySecret(secret),\n\t\tkeyCiphertext: encryptApiKeySecret(secret),\n\t\treferenceId: input.userId,\n\t\tmetadata,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn record;\n}\n/** Returns an existing org-platform key secret or creates one when missing. */\nasync function ensureOrgPlatformApiKey(input) {\n\tconst row = await selectApiKeyByConfigName(ORG_PLATFORM_API_KEY_CONFIG_ID, input.name);\n\tif (row?.keyCiphertext && isActiveApiKey(row)) {\n\t\tif (parseOrgPlatformApiKeyMetadata(row.metadata)?.organizationId === input.organizationId) return decryptApiKeySecret(row.keyCiphertext);\n\t}\n\treturn (await createOrgPlatformApiKey(input)).secret;\n}\nfunction mcpProjectApiKeyName(organizationId, projectSlug) {\n\treturn `mcp:${organizationId}:${projectSlug}`;\n}\nasync function selectOrgPlatformApiKeyForOrganization(apiKeyId, organizationId) {\n\tconst row = await selectApiKeyById(apiKeyId);\n\tif (!row || row.configId !== \"org-platform\") return null;\n\tconst record = parseOrgPlatformRow(row);\n\tif (!record) return null;\n\tif (parseOrgPlatformApiKeyMetadata(row.metadata)?.organizationId !== organizationId) return null;\n\treturn record;\n}\nasync function revokeOrgPlatformApiKey(apiKeyId, organizationId) {\n\tif (!await selectOrgPlatformApiKeyForOrganization(apiKeyId, organizationId)) throw new OrgPlatformApiKeyNotFoundError();\n\tawait deleteApiKeyById(apiKeyId);\n}\nasync function verifyOrgPlatformApiKeySecret(secret) {\n\tif (!secret.startsWith(\"sk_\")) return null;\n\tconst row = await selectApiKeyByConfigAndHash(ORG_PLATFORM_API_KEY_CONFIG_ID, hashApiKeySecret(secret));\n\tif (!row || !isActiveApiKey(row)) return null;\n\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\tif (!metadata) return null;\n\treturn {\n\t\tapiKeyId: row.id,\n\t\torganizationId: metadata.organizationId,\n\t\tuserId: metadata.createdByUserId\n\t};\n}\nasync function loadOrgPlatformApiKeyUser(userId) {\n\treturn await selectUserById(userId) ?? null;\n}\nfunction mapOrgPlatformApiKeyCreator(user) {\n\treturn {\n\t\tid: user.id,\n\t\tname: user.name,\n\t\temail: user.email,\n\t\tavatarUrl: user.image ?? void 0\n\t};\n}\nfunction mapOrgPlatformApiKeyCreatorOrDeleted(userId, user) {\n\tif (user) return mapOrgPlatformApiKeyCreator(user);\n\treturn {\n\t\tid: userId,\n\t\tname: \"Deleted user\",\n\t\tdeleted: true\n\t};\n}\n//#endregion\n//#region src/client/workspace-context.ts\nconst storage = new AsyncLocalStorage();\nfunction runWithWorkspaceContext(context, fn) {\n\treturn storage.run(context, fn);\n}\nfunction getWorkspaceContext() {\n\treturn storage.getStore();\n}\nfunction requireWorkspaceContext() {\n\tconst context = getWorkspaceContext();\n\tif (!context) throw new Error(\"Workspace context is not set\");\n\treturn context;\n}\n//#endregion\n//#region src/project-database/runtime-env.ts\nasync function resolveOrgRuntimeDatabase(organizationId) {\n\tconst organization = await selectOrganizationById(organizationId);\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") {\n\t\tconst url = organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}`;\n\t\treturn {\n\t\t\thost: \"\",\n\t\t\tport: 0,\n\t\t\tdatabase: organization.dbSchema,\n\t\t\tuser: \"\",\n\t\t\tpassword: \"\",\n\t\t\tsearchPath: \"\",\n\t\t\turl\n\t\t};\n\t}\n\tconst platform = resolvePlatformPostgresConfig();\n\treturn {\n\t\thost: platform.host,\n\t\tport: platform.port,\n\t\tdatabase: platform.database,\n\t\tuser: qualifyConnectionUser(organization.dbUser),\n\t\tpassword: decryptCredentialPayload$1(organization.dbPasswordCiphertext),\n\t\tsearchPath: organization.dbSchema\n\t};\n}\n//#endregion\n//#region src/project-database/ensure-pgboss-grants.ts\nasync function ensureOrgPgBossGrants() {\n\tconst { Pool: PgPool } = loadPg();\n\tconst pool = new PgPool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst rows = await getDb().select({ dbUser: organizations.dbUser }).from(organizations).where(isNull(organizations.deletedAt));\n\t\tconst users = [...new Set(rows.map((row) => row.dbUser))];\n\t\tfor (const dbUser of users) await grantPgBossAccess(pool, dbUser);\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n/** @deprecated Use {@link ensureOrgPgBossGrants}. */\nconst ensureProjectPgBossGrants = ensureOrgPgBossGrants;\n//#endregion\n//#region src/org-storage/resolve-config.ts\nfunction hasOrgStorageConfig(organization) {\n\treturn !!organization.storageBucket && !!organization.storageEndpoint && !!organization.storageAccessKeyIdCiphertext && !!organization.storageSecretAccessKeyCiphertext;\n}\nfunction resolveOrgStorageConfig(organization) {\n\tif (!hasOrgStorageConfig(organization)) throw new Error(\"Organization storage is not configured\");\n\treturn {\n\t\tbucket: organization.storageBucket,\n\t\tendpoint: organization.storageEndpoint,\n\t\taccessKeyId: decryptCredentialPayload$1(organization.storageAccessKeyIdCiphertext),\n\t\tsecretAccessKey: decryptCredentialPayload$1(organization.storageSecretAccessKeyCiphertext),\n\t\tregion: organization.storageRegion ?? \"us-east-1\",\n\t\tforcePathStyle: organization.storageForcePathStyle ?? true\n\t};\n}\n//#endregion\n//#region src/org-storage/client.ts\nfunction createOrgStorageClient(organization) {\n\treturn createStorage(resolveOrgStorageConfig(organization));\n}\nfunction createOrgAgentStorageClient(organization, agentId) {\n\tconst config = resolveOrgStorageConfig(organization);\n\tconst bucket = orgAgentBucketName({\n\t\torgBucket: config.bucket,\n\t\tagentId\n\t});\n\treturn createStorage({\n\t\t...config,\n\t\tbucket\n\t});\n}\nfunction createOrgContainerPresign(organization) {\n\treturn createContainerPresignStorage(resolveOrgStorageConfig(organization));\n}\n//#endregion\n//#region src/org-storage/runtime-env.ts\nfunction orgStorageRuntimeEnv(config, containerEnv) {\n\treturn {\n\t\tSTORAGE_ACCESS_KEY_ID: config.accessKeyId,\n\t\tSTORAGE_SECRET_ACCESS_KEY: config.secretAccessKey,\n\t\tSTORAGE_ENDPOINT: containerEnv ? containerPresignEndpointFromEnv(config.endpoint, containerEnv) : config.endpoint,\n\t\tSTORAGE_REGION: config.region,\n\t\tSTORAGE_FORCE_PATH_STYLE: String(config.forcePathStyle),\n\t\tKEYSTROKE_WORKSPACES_BUCKET: config.bucket\n\t};\n}\nfunction orgWorkspacesRuntimeEnv(organization, options) {\n\tif (!hasOrgStorageConfig(organization)) return {};\n\treturn orgStorageRuntimeEnv(resolveOrgStorageConfig(organization), options?.containerEnv);\n}\n//#endregion\n//#region src/org-redis/runtime-env.ts\n/**\n* Per-org Redis env for org machines. Uses the restricted ACL connection string\n* when provisioned; otherwise falls back to the platform admin URL (pre-backfill).\n*/\nfunction orgSchedulerRuntimeEnv(organization, platformEnv = process.env) {\n\tconst orgUrl = organization.redisUrlCiphertext?.trim();\n\tif (orgUrl) {\n\t\tconst result = { REDIS_URL: decryptCredentialPayload$1(orgUrl) };\n\t\tconst prefix = platformEnv.KEYSTROKE_QUEUE_PREFIX?.trim();\n\t\tif (prefix) result.KEYSTROKE_QUEUE_PREFIX = prefix;\n\t\treturn result;\n\t}\n\tconst adminUrl = platformEnv.UPSTASH_REDIS_URL?.trim() || platformEnv.REDIS_URL?.trim() || void 0;\n\tif (!adminUrl) return {};\n\tconst fallback = { REDIS_URL: adminUrl };\n\tconst prefix = platformEnv.KEYSTROKE_QUEUE_PREFIX?.trim();\n\tif (prefix) fallback.KEYSTROKE_QUEUE_PREFIX = prefix;\n\treturn fallback;\n}\n//#endregion\n//#region src/queries/_internal/organization-scope.ts\nfunction eqOrganizationScope(table) {\n\treturn eq$1(table.organizationId, requireOrganizationScopeId());\n}\nfunction scopedAnd(table, ...conditions) {\n\treturn and$1(eqOrganizationScope(table), ...conditions);\n}\nfunction organizationScopeId() {\n\treturn requireOrganizationScopeId();\n}\n//#endregion\n//#region src/queries/oauth-apps/index.ts\nasync function selectOAuthAppBySlug(slug) {\n\treturn (await getDb().select().from(oauthApps).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug))).limit(1))[0];\n}\nasync function selectOAuthAppById(id) {\n\treturn (await getDb().select().from(oauthApps).where(scopedAnd(oauthApps, eq$1(oauthApps.id, id))).limit(1))[0];\n}\nasync function insertOAuthApp(values) {\n\tawait getDb().insert(oauthApps).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t});\n}\nasync function updateOAuthAppBySlug(slug, values) {\n\tawait getDb().update(oauthApps).set(values).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug)));\n}\n//#endregion\n//#region src/queries/oauth-apps/global.ts\n/** Org-unscoped lookup — used before organization scope is known (e.g. inbound Slack webhooks). */\nasync function listOAuthAppsBySlugUnscoped(slug) {\n\treturn getDb().select().from(oauthApps).where(eq$1(oauthApps.slug, slug));\n}\n//#endregion\n//#region src/queries/oauth-connections/index.ts\nasync function selectOAuthConnectionById(id) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.id, id))).limit(1))[0]?.connection;\n}\nasync function selectOAuthConnectionsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, inArray$1(oauthConnections.id, ids)))).map((row) => row.connection);\n}\nasync function selectOAuthConnectionByAppAndExternalId(appId, externalId) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.appId, appId), eq$1(oauthConnections.externalId, externalId))).limit(1))[0]?.connection;\n}\nasync function listOAuthConnectionsByAppId(appId) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.appId, appId)))).map((row) => row.connection);\n}\nasync function deleteOAuthConnectionById(id) {\n\tif (!await selectOAuthConnectionById(id)) return false;\n\tawait getDb().delete(oauthConnections).where(eq$1(oauthConnections.id, id));\n\treturn true;\n}\nasync function insertOAuthConnection(values) {\n\tawait getDb().insert(oauthConnections).values(values);\n}\n/** Returns the id of the persisted row: the existing row's id on update, `values.id` on insert. */\nasync function upsertOAuthConnection(values) {\n\tconst existing = await selectOAuthConnectionByAppAndExternalId(values.appId, values.externalId);\n\tif (existing) {\n\t\tawait getDb().update(oauthConnections).set({\n\t\t\taccessTokenCiphertext: values.accessTokenCiphertext,\n\t\t\trefreshTokenCiphertext: values.refreshTokenCiphertext,\n\t\t\taccessTokenExpiresAt: values.accessTokenExpiresAt,\n\t\t\tgrantedScopes: values.grantedScopes && values.grantedScopes.length > 0 ? values.grantedScopes : existing.grantedScopes,\n\t\t\tmetadata: values.metadata,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(oauthConnections.id, existing.id));\n\t\treturn existing.id;\n\t}\n\tawait insertOAuthConnection(values);\n\treturn values.id;\n}\n//#endregion\n//#region src/queries/oauth-connections/global.ts\n/** Org-unscoped lookup — resolves a Slack team_id (externalId) to org + connection via oauth_apps.slug. */\nasync function selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId) {\n\treturn getDb().select({\n\t\torganizationId: oauthApps.organizationId,\n\t\tconnectionId: oauthConnections.id,\n\t\tappId: oauthApps.id,\n\t\texternalId: oauthConnections.externalId\n\t}).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(and$1(eq$1(oauthApps.slug, appSlug), eq$1(oauthConnections.externalId, externalId)));\n}\n//#endregion\n//#region src/queries/secret-values/index.ts\nasync function selectSecretValue(refKind, refId, field) {\n\treturn (await getDb().select().from(secretValues).where(scopedAnd(secretValues, eq$1(secretValues.refKind, refKind), eq$1(secretValues.refId, refId), eq$1(secretValues.field, field))).limit(1))[0];\n}\nasync function upsertSecretValue(values) {\n\tconst db = getDb();\n\tconst existing = await selectSecretValue(values.refKind, values.refId, values.field);\n\tif (existing) {\n\t\tawait db.update(secretValues).set({\n\t\t\tciphertext: values.ciphertext,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(secretValues.id, existing.id));\n\t\treturn;\n\t}\n\tawait db.insert(secretValues).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t});\n}\nasync function deleteSecretValuesForRef(refKind, refId) {\n\tawait getDb().delete(secretValues).where(scopedAnd(secretValues, eq$1(secretValues.refKind, refKind), eq$1(secretValues.refId, refId)));\n}\n//#endregion\n//#region src/oauth/app.ts\nfunction metadataMatches(existing, next) {\n\treturn JSON.stringify(existing ?? null) === JSON.stringify(next ?? null);\n}\nfunction oauthAppValuesDiffer(existing, options) {\n\tconst nextSigningSecret = options.signingSecret ?? \"\";\n\treturn existing.clientId !== options.clientId || existing.clientSecret !== options.clientSecret || existing.signingSecret !== nextSigningSecret || !metadataMatches(existing.metadata, options.metadata ?? null);\n}\nfunction encryptOAuthAppValues(options) {\n\treturn {\n\t\tclientIdCiphertext: encryptCredentialPayload$1(options.clientId),\n\t\tclientSecretCiphertext: encryptCredentialPayload$1(options.clientSecret),\n\t\tsigningSecretCiphertext: options.signingSecret ? encryptCredentialPayload$1(options.signingSecret) : null,\n\t\tmetadata: options.metadata ?? null\n\t};\n}\nfunction decryptOAuthAppRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tprovider: row.provider,\n\t\tslug: row.slug,\n\t\ttokenStrategy: row.tokenStrategy,\n\t\tclientId: decryptCredentialPayload$1(row.clientIdCiphertext),\n\t\tclientSecret: decryptCredentialPayload$1(row.clientSecretCiphertext),\n\t\tsigningSecret: row.signingSecretCiphertext ? decryptCredentialPayload$1(row.signingSecretCiphertext) : \"\",\n\t\tredirectUri: row.redirectUri,\n\t\tmetadata: row.metadata ?? null\n\t};\n}\nasync function getDecryptedOAuthAppBySlug(slug) {\n\tconst row = await selectOAuthAppBySlug(slug);\n\tif (!row) return null;\n\treturn decryptOAuthAppRow(row);\n}\nasync function getDecryptedOAuthAppById(id) {\n\tconst row = await selectOAuthAppById(id);\n\tif (!row) return null;\n\treturn decryptOAuthAppRow(row);\n}\nasync function ensureOAuthApp(options) {\n\tconst existing = await selectOAuthAppBySlug(options.slug);\n\tif (existing) {\n\t\tif (!oauthAppValuesDiffer(decryptOAuthAppRow(existing), options)) return {\n\t\t\tid: existing.id,\n\t\t\tcreated: false,\n\t\t\tupdated: false\n\t\t};\n\t\tawait updateOAuthAppBySlug(options.slug, {\n\t\t\t...encryptOAuthAppValues(options),\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t});\n\t\treturn {\n\t\t\tid: existing.id,\n\t\t\tcreated: false,\n\t\t\tupdated: true\n\t\t};\n\t}\n\tconst now = /* @__PURE__ */ new Date();\n\tconst id = crypto.randomUUID();\n\tawait insertOAuthApp({\n\t\tid,\n\t\tprovider: options.provider,\n\t\tslug: options.slug,\n\t\ttokenStrategy: options.tokenStrategy,\n\t\t...encryptOAuthAppValues(options),\n\t\tredirectUri: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn {\n\t\tid,\n\t\tcreated: true,\n\t\tupdated: false\n\t};\n}\n//#endregion\n//#region src/oauth/connection.ts\nfunction decryptOAuthConnectionRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tappId: row.appId,\n\t\texternalId: row.externalId,\n\t\taccessToken: decryptCredentialPayload$1(row.accessTokenCiphertext),\n\t\trefreshToken: row.refreshTokenCiphertext ? decryptCredentialPayload$1(row.refreshTokenCiphertext) : null,\n\t\taccessTokenExpiresAt: row.accessTokenExpiresAt ?? null,\n\t\tgrantedScopes: row.grantedScopes ?? null,\n\t\tmetadata: row.metadata ?? null\n\t};\n}\nasync function getDecryptedOAuthConnectionById(id) {\n\tconst row = await selectOAuthConnectionById(id);\n\tif (!row) return null;\n\treturn decryptOAuthConnectionRow(row);\n}\nasync function getDecryptedOAuthConnectionsByAppSlug(appSlug) {\n\tconst app = await selectOAuthAppBySlug(appSlug);\n\tif (!app) return [];\n\treturn (await listOAuthConnectionsByAppId(app.id)).map(decryptOAuthConnectionRow);\n}\nasync function getDecryptedOAuthConnectionByAppSlugAndExternalId(appSlug, externalId) {\n\tconst app = await selectOAuthAppBySlug(appSlug);\n\tif (!app) return null;\n\tconst row = await selectOAuthConnectionByAppAndExternalId(app.id, externalId);\n\tif (!row) return null;\n\treturn decryptOAuthConnectionRow(row);\n}\nasync function saveOAuthConnection(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\treturn upsertOAuthConnection({\n\t\tid: options.connectionId ?? crypto.randomUUID(),\n\t\tappId: options.appId,\n\t\texternalId: options.externalId,\n\t\taccessTokenCiphertext: encryptCredentialPayload$1(options.accessToken),\n\t\trefreshTokenCiphertext: options.refreshToken ? encryptCredentialPayload$1(options.refreshToken) : null,\n\t\taccessTokenExpiresAt: options.accessTokenExpiresAt ?? null,\n\t\tgrantedScopes: options.grantedScopes ?? null,\n\t\tmetadata: options.metadata ?? null,\n\t\tconnectedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n//#endregion\n//#region src/oauth/mcp-refresh.ts\nasync function refreshMcpOAuthToken(params) {\n\tconst tokenEndpoint = params.tokenEndpoint?.trim();\n\tif (!tokenEndpoint) throw new Error(\"MCP OAuth refresh requires tokenEndpoint in app metadata\");\n\tconst body = new URLSearchParams({\n\t\tgrant_type: \"refresh_token\",\n\t\trefresh_token: params.refreshToken,\n\t\tclient_id: params.clientId\n\t});\n\tif (params.clientSecret) body.set(\"client_secret\", params.clientSecret);\n\tconst response = await fetch(tokenEndpoint, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\tAccept: \"application/json\"\n\t\t},\n\t\tbody\n\t});\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`MCP OAuth refresh failed (${response.status}): ${text}`);\n\t}\n\tconst payload = await response.json();\n\treturn {\n\t\taccessToken: payload.access_token,\n\t\trefreshToken: payload.refresh_token,\n\t\taccessTokenExpiresAt: payload.expires_in && payload.expires_in > 0 ? new Date(Date.now() + payload.expires_in * 1e3) : void 0\n\t};\n}\nfunction readMcpTokenEndpoint(metadata) {\n\treturn metadata?.tokenEndpoint?.trim() || void 0;\n}\n//#endregion\n//#region src/oauth/refresh-token.ts\nconst TOKEN_EXPIRY_BUFFER_MS = 6e4;\nfunction oauthClientSecretForRefresh(app) {\n\tif (app.metadata?.tokenEndpointAuthMethod === \"none\") return \"\";\n\treturn app.clientSecret?.trim() ?? \"\";\n}\nfunction accessTokenIsStale(expiresAt) {\n\tif (!expiresAt) return true;\n\treturn expiresAt.getTime() <= Date.now() + TOKEN_EXPIRY_BUFFER_MS;\n}\nasync function resolveOAuthAccessToken(connection, app, tokenRefresh) {\n\tif (app.tokenStrategy === \"installation\" || app.tokenStrategy === \"app_installation\") return connection.accessToken;\n\tif (!accessTokenIsStale(connection.accessTokenExpiresAt)) return connection.accessToken;\n\tif (!connection.refreshToken) {\n\t\tif (!connection.accessTokenExpiresAt) return connection.accessToken;\n\t\tthrow new Error(`OAuth connection \"${connection.id}\" is missing a refresh token.`);\n\t}\n\tconst refresh = tokenRefresh?.get(app.slug) ?? (app.provider === \"mcp\" ? refreshMcpOAuthToken : void 0);\n\tif (!refresh) throw new Error(`OAuth refresh is not registered for app \"${app.slug}\".`);\n\tconst refreshed = await refresh({\n\t\tclientId: app.clientId,\n\t\tclientSecret: oauthClientSecretForRefresh(app),\n\t\trefreshToken: connection.refreshToken,\n\t\ttokenEndpoint: readMcpTokenEndpoint(app.metadata)\n\t});\n\tawait saveOAuthConnection({\n\t\tappId: connection.appId,\n\t\texternalId: connection.externalId,\n\t\taccessToken: refreshed.accessToken,\n\t\trefreshToken: refreshed.refreshToken ?? connection.refreshToken,\n\t\taccessTokenExpiresAt: refreshed.accessTokenExpiresAt,\n\t\tgrantedScopes: connection.grantedScopes ?? void 0,\n\t\tmetadata: connection.metadata ?? void 0,\n\t\tconnectionId: connection.id\n\t});\n\treturn refreshed.accessToken;\n}\n//#endregion\n//#region src/oauth/global-lookup.ts\n/** Signing secret for inbound webhooks before org scope is known (shared managed Slack app). */\nasync function getOAuthAppSigningSecretBySlugGlobal(appSlug) {\n\tconst fromEnv = process.env.SLACK_SIGNING_SECRET?.trim();\n\tif (fromEnv) return fromEnv;\n\tconst apps = await listOAuthAppsBySlugUnscoped(appSlug);\n\tfor (const app of apps) if (app.signingSecretCiphertext) return decryptCredentialPayload$1(app.signingSecretCiphertext);\n\treturn null;\n}\n/** All orgs connected to a Slack workspace (team_id). */\nasync function listOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId) {\n\treturn (await selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId)).map((row) => ({\n\t\torganizationId: row.organizationId,\n\t\tconnectionId: row.connectionId\n\t}));\n}\n/** Bot token for a team from any org's connection (same Slack app + team → same token). */\nasync function getGlobalOAuthAccessTokenByAppSlugAndExternalId(appSlug, externalId) {\n\tconst first = (await selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId))[0];\n\tif (!first) return null;\n\tconst connection = await selectOAuthConnectionById(first.connectionId);\n\tif (!connection) return null;\n\treturn decryptCredentialPayload$1(connection.accessTokenCiphertext);\n}\n//#endregion\n//#region src/queries/apps/slug.ts\nasync function isOrgAppSlugTaken(orgSlug, slugPart) {\n\tconst qualified = qualifyOrgSlug(orgSlug, slugPart);\n\treturn (await getDb().select({ id: apps.id }).from(apps).where(eq$1(apps.slug, qualified)).limit(1)).length > 0;\n}\nasync function resolveAvailableOrgAppSlug(orgSlug, nameOrSlug) {\n\tconst base = slugifyAppName(nameOrSlug);\n\tif (!await isOrgAppSlugTaken(orgSlug, base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = AppSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isOrgAppSlugTaken(orgSlug, candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique app slug\");\n}\nasync function checkOrgAppSlugAvailability(orgSlug, slugPart) {\n\tconst normalized = slugPart.trim().toLowerCase();\n\tconst format = AppSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (await isOrgAppSlugTaken(orgSlug, parsed)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableOrgAppSlug(orgSlug, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\n//#endregion\n//#region src/queries/apps/index.ts\nvar OrgAppSlugTakenError = class extends Error {\n\tslug;\n\tconstructor(slug) {\n\t\tsuper(`App slug already exists: ${slug}`);\n\t\tthis.name = \"OrgAppSlugTakenError\";\n\t\tthis.slug = slug;\n\t}\n};\nasync function selectAppBySlug(slug) {\n\treturn (await getDb().select().from(apps).where(eq$1(apps.slug, slug)).limit(1))[0];\n}\nasync function listOfficialApps() {\n\treturn getDb().select().from(apps).where(isNull$1(apps.organizationId));\n}\nasync function listAppsForOrganization(organizationId) {\n\treturn getDb().select().from(apps).where(or(isNull$1(apps.organizationId), eq$1(apps.organizationId, organizationId)));\n}\nasync function selectAppForOrganization(organizationId, slug) {\n\tconst row = await selectAppBySlug(slug);\n\tif (!row) return;\n\tif (row.organizationId === null || row.organizationId === organizationId) return row;\n}\nasync function createOrgApp(values) {\n\tconst db = getDb();\n\tconst slug = qualifyOrgSlug(values.orgSlug, values.slug);\n\tif (await selectAppBySlug(slug)) throw new OrgAppSlugTakenError(slug);\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.insert(apps).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: values.organizationId,\n\t\tslug,\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tcategory: \"Custom\",\n\t\tlogo: null,\n\t\tauthKind: values.authKind,\n\t\toauthScopes: values.oauthScopes ?? [],\n\t\tcredentialFields: values.credentialFields ?? {},\n\t\tcredentialScheme: values.credentialScheme ?? null,\n\t\turl: values.url ?? null,\n\t\tsource: values.source,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning())[0];\n}\nasync function upsertOfficialApp(values) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (await selectAppBySlug(values.slug)) return (await db.update(apps).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tcategory: values.category,\n\t\t...values.logo !== void 0 ? { logo: values.logo } : {},\n\t\tauthKind: values.authKind,\n\t\toauthScopes: values.oauthScopes,\n\t\tsource: values.source,\n\t\t...values.credentialFields !== void 0 ? { credentialFields: values.credentialFields } : {},\n\t\t...values.credentialScheme !== void 0 ? { credentialScheme: values.credentialScheme } : {},\n\t\tupdatedAt: now\n\t}).where(eq$1(apps.slug, values.slug)).returning())[0];\n\treturn (await db.insert(apps).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: null,\n\t\tcredentialFields: values.credentialFields ?? {},\n\t\tcredentialScheme: values.credentialScheme ?? null,\n\t\t...values,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning())[0];\n}\nfunction hasCredentialFieldTemplate(row) {\n\treturn Object.keys(row.credentialFields).length > 0;\n}\nasync function selectOrgAppBySlug(organizationId, slug) {\n\treturn (await getDb().select().from(apps).where(and$1(eq$1(apps.slug, slug), eq$1(apps.organizationId, organizationId))).limit(1))[0];\n}\n//#endregion\n//#region src/apps/seed.ts\n/** Upsert official apps from a hosted manifest. Idempotent — safe to run on a schedule. */\nasync function seedOfficialApps(entries) {\n\tfor (const entry of entries) await upsertOfficialApp({\n\t\tslug: entry.slug,\n\t\tname: entry.name,\n\t\tdescription: entry.description,\n\t\tcategory: entry.category,\n\t\t...entry.logo !== void 0 ? { logo: entry.logo } : {},\n\t\tauthKind: entry.authKind,\n\t\toauthScopes: entry.oauthScopes,\n\t\tsource: entry.source\n\t});\n}\n//#endregion\nexport { CannotModifyOwnerError, DEFAULT_PLATFORM_DATABASE_URL, DEFAULT_STANDALONE_ORGANIZATION_ID, DEFAULT_STANDALONE_ORGANIZATION_NAME, DEFAULT_STANDALONE_ORGANIZATION_SLUG, DEFAULT_STANDALONE_PROJECT_NAME, DEFAULT_STANDALONE_PROJECT_SLUG, LastOwnerError, ORG_PLATFORM_API_KEY_CONFIG_ID, OrgAppSlugTakenError, OrgPlatformApiKeyNotFoundError, OrganizationInvitationExpiredError, OrganizationInvitationForbiddenError, OrganizationInvitationNotFoundError, OrganizationMemberNotFoundError, OrganizationSlugTakenError, ProjectMemberNotFoundError, ProjectSlugTakenError, WEBHOOK_API_KEY_CONFIG_ID, acceptInvitation, apps, backfillProjectUsers, buildDefaultProjectDescription, buildDefaultProjectForUser, buildOrgDatabaseUrl, buildOrgRedisUrl, checkOrgAppSlugAvailability, checkOrganizationSlugAvailability, checkProjectSlugAvailability, closeDatabase, completeProjectArtifact, createConnection, createOrgAgentStorageClient, createOrgApp, createOrgContainerPresign, createOrgPlatformApiKey, createOrgStorageClient, createOrganizationForUser, createPgConnection, createProjectForOrganization, createSqliteConnection, declineInvitation, decryptCredentialPayload, deleteOAuthConnectionById, deleteProjectForOrganization, deleteSecretValuesForRef, deprovisionOrgDatabase, deprovisionOrgRedis, encryptCredentialPayload, ensureDefaultOrganization, ensureDefaultOrganizationAndProject, ensureDefaultProject, ensureDefaultProjectForUser, ensureDefaultProjectForUserInTransaction, ensureOAuthApp, ensureOrgPgBossGrants, ensureOrgPlatformApiKey, ensureProjectPgBossGrants, ensureWebhookApiKeyForRoute, ensureWebhookApiKeys, findOrCreateUserByEmail, firstNameFromUser, getDatabaseHandle, getDecryptedOAuthAppById, getDecryptedOAuthAppBySlug, getDecryptedOAuthConnectionByAppSlugAndExternalId, getDecryptedOAuthConnectionById, getDecryptedOAuthConnectionsByAppSlug, getGlobalOAuthAccessTokenByAppSlugAndExternalId, getOAuthAppSigningSecretBySlugGlobal, getOrganizationScopeId, getWorkspaceContext, hasCredentialFieldTemplate, initDatabase, insertOAuthApp, insertProjectArtifact, inviteOrganizationMembers, inviteProjectMembers, isDatabaseInitialized, isOrganizationStorageBucketInUse, isStandaloneMode, listAppsForOrganization, listOAuthAppsBySlugUnscoped, listOAuthConnectionsByAppId, listOAuthInstallationsByAppSlugAndExternalId, listOfficialApps, listOrgPlatformApiKeysForOrganization, listOrgPlatformApiKeysForUser, listWebhookApiKeys, listWebhookApiKeysForProject, loadOrgPlatformApiKeyUser, mapOrgPlatformApiKeyCreator, mapOrgPlatformApiKeyCreatorOrDeleted, mcpProjectApiKeyName, normalizeUserEmail, orgDbRoleName, orgDbSchemaName, orgRedisAclSetUserArgs, orgRedisQueueSegment, orgRedisUsername, orgSchedulerRuntimeEnv, orgWorkspacesRuntimeEnv, organizationInvitationStatuses, organizationRowToSidebarBranding, organizationUserRoles, projectArtifactStatuses, projectStatuses, promoteProjectArtifact, provisionOrgDatabase, provisionOrgRedis, removeOrganizationMember, removeProjectMember, requireOrganizationScopeId, requireWorkspaceContext, resolveMigrationsFolder, resolveNewOrganizationIdentity, resolveOAuthAccessToken, resolveOrgDatabaseUrl, resolveOrgProjectDatabaseOptions, resolveOrgRuntimeDatabase, resolveOrgStorageConfig, revokeOrgPlatformApiKey, runMigrations, runWithOrganizationScope, runWithStandaloneScope, runWithWorkspaceContext, saveOAuthConnection, seedOfficialApps, selectActiveArtifactManifestForProject, selectActiveArtifactManifestsByOrganizationId, selectActiveArtifactSourceManifestForProject, selectActiveOrganizationIds, selectActiveProjectArtifactForProject, selectAppBySlug, selectAppForOrganization, selectLastDeploymentAtByProject, selectOAuthAppById, selectOAuthAppBySlug, selectOAuthConnectionByAppAndExternalId, selectOAuthConnectionById, selectOAuthConnectionsByIds, selectOAuthInstallationsByAppSlugAndExternalId, selectOrgAppBySlug, selectOrgPlatformApiKeyForOrganization, selectOrganizationById, selectOrganizationBySlug, selectOrganizationMembers, selectOrganizationUsersByUserId, selectPendingInvitationsForUser, selectProjectArtifactById, selectProjectArtifactForProject, selectProjectById, selectProjectDeployments, selectProjectForOrganization, selectProjectForOrganizationBySlug, selectProjectIdsForUser, selectProjectMembers, selectProjectsByOrganizationId, selectSecretValue, selectUserByEmail, selectUserById, selectUserByNormalizedEmail, selectUserOrganization, selectUserOrganizationMembership, selectUserOrganizations, selectUserProjectMembership, selectUsersByIds, updateOAuthAppBySlug, updateOrganizationActive, updateOrganizationFailed, updateOrganizationMemberRole, updateOrganizationName, updateOrganizationSidebarBranding, updateOrganizationSlug, updateProjectActive, updateProjectArtifactManifest, updateProjectArtifactSourceManifest, updateProjectFailed, updateProjectForOrganization, updateProjectMemberRole, updateProjectSettings, updateUserById, upsertOAuthConnection, upsertOfficialApp, upsertProjectMember, upsertSecretValue, verifyOrgPlatformApiKeySecret, verifyWebhookApiKeyForRoute, webhookApiKeyName, webhookEndpointSuffix };\n\n//# sourceMappingURL=index.mjs.map","import { clearCredentialInstanceDefaults, deleteCredentialAssignmentById, deleteCredentialInstanceById, ensureKeystrokeCredentialInstance, ensureOAuthCredentialInstance as ensureOAuthCredentialInstance$1, getProjectScopeId, getServerTenantScopeId, listCredentialAssignmentsByTarget, listCredentialInstancesByScope, listDistinctAssignmentConsumerIds, listRecentWorkflowStepConsumers, selectCredentialAssignmentById, selectCredentialInstanceById, selectCredentialInstancesForScope, touchCredentialInstanceLastUsed, upsertCredentialAssignment, upsertCredentialInstance } from \"@keystrokehq/database\";\nimport { ensureOAuthApp as ensureOAuthApp$1, getDecryptedOAuthAppById as getDecryptedOAuthAppById$1, getDecryptedOAuthAppBySlug, getDecryptedOAuthConnectionByAppSlugAndExternalId, getDecryptedOAuthConnectionById as getDecryptedOAuthConnectionById$1, getDecryptedOAuthConnectionsByAppSlug, resolveOAuthAccessToken, saveOAuthConnection as saveOAuthConnection$1 } from \"@keystrokehq/platform-database\";\n//#region src/store/credential-assignments.ts\nfunction normalizeRow(row) {\n\tconst { projectId: _projectId, ...rest } = row;\n\treturn rest;\n}\nasync function listCredentialAssignmentsByTarget$1(options) {\n\treturn (await listCredentialAssignmentsByTarget(options)).map(normalizeRow);\n}\nasync function selectCredentialAssignmentById$1(id) {\n\tconst row = await selectCredentialAssignmentById(id);\n\treturn row ? normalizeRow(row) : void 0;\n}\nasync function upsertCredentialAssignment$1(values) {\n\treturn normalizeRow(await upsertCredentialAssignment(values));\n}\nasync function deleteCredentialAssignmentById$1(id) {\n\treturn deleteCredentialAssignmentById(id);\n}\nasync function listDistinctAssignmentConsumerIds$1(options) {\n\treturn listDistinctAssignmentConsumerIds(options);\n}\nasync function listRecentWorkflowStepConsumers$1(workflowSlug, runLimit) {\n\treturn listRecentWorkflowStepConsumers(workflowSlug, runLimit);\n}\n//#endregion\n//#region src/store/credential-instances.ts\nfunction normalizeLocalRow(row) {\n\tconst { projectId: _projectId, ...rest } = row;\n\treturn rest;\n}\nasync function selectCredentialInstanceById$1(id) {\n\tconst row = await selectCredentialInstanceById(id);\n\treturn row ? normalizeLocalRow(row) : void 0;\n}\nasync function selectCredentialInstancesForScope$1(appSlug, scopeType, scopeId) {\n\treturn (await selectCredentialInstancesForScope(appSlug, scopeType, scopeId)).map(normalizeLocalRow);\n}\nasync function listCredentialInstancesByScope$1(options) {\n\treturn (await listCredentialInstancesByScope(options)).map(normalizeLocalRow);\n}\nasync function upsertCredentialInstance$1(values) {\n\tawait upsertCredentialInstance(values);\n}\nasync function deleteCredentialInstanceById$1(id) {\n\treturn deleteCredentialInstanceById(id);\n}\nasync function touchCredentialInstanceLastUsed$1(id) {\n\tawait touchCredentialInstanceLastUsed(id);\n}\nasync function clearCredentialInstanceDefaults$1(options) {\n\tawait clearCredentialInstanceDefaults(options);\n}\nasync function listCredentialInstancesForAssignment(options) {\n\tconst tenantScopeId = getServerTenantScopeId();\n\tconst projectId = getProjectScopeId();\n\tconst rows = [];\n\tconst appendScope = async (scopeType, scopeId) => {\n\t\trows.push(...await listCredentialInstancesByScope$1({\n\t\t\t...options.appSlug ? { appSlug: options.appSlug } : {},\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t};\n\tif (options.appSlug) {\n\t\tawait appendScope(\"organization\", tenantScopeId);\n\t\tawait appendScope(\"project\", projectId);\n\t\tif (options.userId) await appendScope(\"user\", options.userId);\n\t\treturn rows;\n\t}\n\tawait appendScope(\"organization\", tenantScopeId);\n\tawait appendScope(\"project\", projectId);\n\tif (options.userId) await appendScope(\"user\", options.userId);\n\treturn rows;\n}\n//#endregion\n//#region src/store/oauth.ts\nasync function resolveOAuthAccessTokenForStore(connection, app, tokenRefresh) {\n\treturn resolveOAuthAccessToken(connection, app, tokenRefresh);\n}\n//#endregion\nexport { selectCredentialAssignmentById$1 as C, listRecentWorkflowStepConsumers$1 as S, touchCredentialInstanceLastUsed$1 as _, getDecryptedOAuthAppBySlug as a, listCredentialAssignmentsByTarget$1 as b, getDecryptedOAuthConnectionsByAppSlug as c, clearCredentialInstanceDefaults$1 as d, deleteCredentialInstanceById$1 as f, selectCredentialInstancesForScope$1 as g, selectCredentialInstanceById$1 as h, getDecryptedOAuthAppById$1 as i, resolveOAuthAccessTokenForStore as l, listCredentialInstancesForAssignment as m, ensureOAuthApp$1 as n, getDecryptedOAuthConnectionByAppSlugAndExternalId as o, listCredentialInstancesByScope$1 as p, ensureOAuthCredentialInstance$1 as r, getDecryptedOAuthConnectionById$1 as s, ensureKeystrokeCredentialInstance as t, saveOAuthConnection$1 as u, upsertCredentialInstance$1 as v, upsertCredentialAssignment$1 as w, listDistinctAssignmentConsumerIds$1 as x, deleteCredentialAssignmentById$1 as y };\n\n//# sourceMappingURL=store-4At2Wnk9.mjs.map","import { deriveCredentialInstanceSlug } from \"@keystrokehq/shared\";\nimport { clearCredentialInstanceDefaults, encryptCredentialPayload, selectCredentialInstancesForScope, upsertCredentialInstance } from \"@keystrokehq/database\";\nimport { deleteSecretValuesForRef, getOrganizationScopeId, selectSecretValue, upsertSecretValue } from \"@keystrokehq/platform-database\";\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\n//#region src/crypto.ts\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_LENGTH = 12;\nfunction resolveEncryptionKey() {\n\tconst secret = process.env.PLATFORM_SECRETS_ENCRYPTION_KEY?.trim() ?? process.env.CREDENTIALS_ENCRYPTION_KEY?.trim();\n\tif (!secret) throw new Error(\"CREDENTIALS_ENCRYPTION_KEY is required\");\n\treturn createHash(\"sha256\").update(secret).digest();\n}\nfunction encryptSecretPayload(plaintext) {\n\tconst iv = randomBytes(IV_LENGTH);\n\tconst cipher = createCipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tconst encrypted = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n\tconst tag = cipher.getAuthTag();\n\treturn Buffer.concat([\n\t\tiv,\n\t\ttag,\n\t\tencrypted\n\t]).toString(\"base64\");\n}\nfunction decryptSecretPayload(ciphertext) {\n\tconst buffer = Buffer.from(ciphertext, \"base64\");\n\tconst iv = buffer.subarray(0, IV_LENGTH);\n\tconst tag = buffer.subarray(IV_LENGTH, 28);\n\tconst encrypted = buffer.subarray(28);\n\tconst decipher = createDecipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tdecipher.setAuthTag(tag);\n\treturn Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(\"utf8\");\n}\n//#endregion\n//#region src/store.ts\nfunction usePlatformStore() {\n\treturn getOrganizationScopeId() !== void 0;\n}\nfunction assertOrganizationScope() {\n\tif (!usePlatformStore()) throw new Error(\"Secret store requires organization scope\");\n}\nfunction createSecretStore() {\n\treturn {\n\t\tasync get(ref) {\n\t\t\tassertOrganizationScope();\n\t\t\tconst row = await selectSecretValue(ref.kind, ref.id, ref.field);\n\t\t\tif (!row) return null;\n\t\t\treturn decryptSecretPayload(row.ciphertext);\n\t\t},\n\t\tasync set(ref, plaintext) {\n\t\t\tassertOrganizationScope();\n\t\t\tconst now = /* @__PURE__ */ new Date();\n\t\t\tconst ciphertext = encryptSecretPayload(plaintext);\n\t\t\tawait upsertSecretValue({\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\trefKind: ref.kind,\n\t\t\t\trefId: ref.id,\n\t\t\t\tfield: ref.field,\n\t\t\t\tciphertext,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t});\n\t\t},\n\t\tasync deleteRef(kind, id) {\n\t\t\tassertOrganizationScope();\n\t\t\tawait deleteSecretValuesForRef(kind, id);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/credential-instance.ts\nasync function setCredentialInstanceSecret(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst siblings = await selectCredentialInstancesForScope(options.key, options.scopeType, options.scopeId);\n\tconst isDefault = options.isDefault ?? siblings.length === 0;\n\tconst name = options.name ?? options.label ?? null;\n\tconst slug = options.slug ?? deriveCredentialInstanceSlug({\n\t\tappSlug: options.key,\n\t\tname,\n\t\ttakenSlugs: siblings.map((row) => row.slug)\n\t});\n\tif (isDefault) await clearCredentialInstanceDefaults({\n\t\tappSlug: options.key,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\texceptId: options.id\n\t});\n\tif (getOrganizationScopeId() !== void 0) {\n\t\tawait upsertCredentialInstance({\n\t\t\tid: options.id,\n\t\t\tappSlug: options.key,\n\t\t\tslug,\n\t\t\tname,\n\t\t\tscopeType: options.scopeType,\n\t\t\tscopeId: options.scopeId,\n\t\t\tlabel: name,\n\t\t\tisDefault,\n\t\t\tauthKind: \"api_key\",\n\t\t\tciphertext: null,\n\t\t\tconnectionId: null,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\tawait createSecretStore().set({\n\t\t\tkind: \"credential_instance\",\n\t\t\tid: options.id,\n\t\t\tfield: \"payload\"\n\t\t}, JSON.stringify(options.value));\n\t\treturn;\n\t}\n\tawait upsertCredentialInstance({\n\t\tid: options.id,\n\t\tappSlug: options.key,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault,\n\t\tauthKind: \"api_key\",\n\t\tciphertext: encryptCredentialPayload(JSON.stringify(options.value)),\n\t\tconnectionId: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n}\nasync function readCredentialInstanceSecret(instanceId) {\n\tif (getOrganizationScopeId() === void 0) return null;\n\treturn createSecretStore().get({\n\t\tkind: \"credential_instance\",\n\t\tid: instanceId,\n\t\tfield: \"payload\"\n\t});\n}\nasync function deleteCredentialInstanceSecret(instanceId) {\n\tif (getOrganizationScopeId() === void 0) return;\n\tawait createSecretStore().deleteRef(\"credential_instance\", instanceId);\n}\n//#endregion\nexport { createSecretStore, decryptSecretPayload, deleteCredentialInstanceSecret, encryptSecretPayload, readCredentialInstanceSecret, setCredentialInstanceSecret };\n\n//# sourceMappingURL=index.mjs.map","'use strict';\n\nconst ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case MAP:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nfunction isNode(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case ALIAS:\n            case MAP:\n            case SCALAR:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexports.ALIAS = ALIAS;\nexports.DOC = DOC;\nexports.MAP = MAP;\nexports.NODE_TYPE = NODE_TYPE;\nexports.PAIR = PAIR;\nexports.SCALAR = SCALAR;\nexports.SEQ = SEQ;\nexports.hasAnchor = hasAnchor;\nexports.isAlias = isAlias;\nexports.isCollection = isCollection;\nexports.isDocument = isDocument;\nexports.isMap = isMap;\nexports.isNode = isNode;\nexports.isPair = isPair;\nexports.isScalar = isScalar;\nexports.isSeq = isSeq;\n","'use strict';\n\nvar identity = require('./nodes/identity.js');\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (identity.isDocument(node)) {\n        const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n    const ctrl = callVisitor(key, node, visitor, path);\n    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visit_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (identity.isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = visit_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (identity.isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = visit_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = visit_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `Promise`: Must resolve to one of the following values\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (identity.isDocument(node)) {\n        const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n    const ctrl = await callVisitor(key, node, visitor, path);\n    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visitAsync_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (identity.isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = await visitAsync_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (identity.isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = await visitAsync_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = await visitAsync_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\nfunction initVisitor(visitor) {\n    if (typeof visitor === 'object' &&\n        (visitor.Collection || visitor.Node || visitor.Value)) {\n        return Object.assign({\n            Alias: visitor.Node,\n            Map: visitor.Node,\n            Scalar: visitor.Node,\n            Seq: visitor.Node\n        }, visitor.Value && {\n            Map: visitor.Value,\n            Scalar: visitor.Value,\n            Seq: visitor.Value\n        }, visitor.Collection && {\n            Map: visitor.Collection,\n            Seq: visitor.Collection\n        }, visitor);\n    }\n    return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n    if (typeof visitor === 'function')\n        return visitor(key, node, path);\n    if (identity.isMap(node))\n        return visitor.Map?.(key, node, path);\n    if (identity.isSeq(node))\n        return visitor.Seq?.(key, node, path);\n    if (identity.isPair(node))\n        return visitor.Pair?.(key, node, path);\n    if (identity.isScalar(node))\n        return visitor.Scalar?.(key, node, path);\n    if (identity.isAlias(node))\n        return visitor.Alias?.(key, node, path);\n    return undefined;\n}\nfunction replaceNode(key, path, node) {\n    const parent = path[path.length - 1];\n    if (identity.isCollection(parent)) {\n        parent.items[key] = node;\n    }\n    else if (identity.isPair(parent)) {\n        if (key === 'key')\n            parent.key = node;\n        else\n            parent.value = node;\n    }\n    else if (identity.isDocument(parent)) {\n        parent.contents = node;\n    }\n    else {\n        const pt = identity.isAlias(parent) ? 'alias' : 'scalar';\n        throw new Error(`Cannot replace node with ${pt} parent`);\n    }\n}\n\nexports.visit = visit;\nexports.visitAsync = visitAsync;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\nconst escapeChars = {\n    '!': '%21',\n    ',': '%2C',\n    '[': '%5B',\n    ']': '%5D',\n    '{': '%7B',\n    '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n    constructor(yaml, tags) {\n        /**\n         * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n         * included in the document's stringified representation.\n         */\n        this.docStart = null;\n        /** The doc-end marker `...`.  */\n        this.docEnd = false;\n        this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n        this.tags = Object.assign({}, Directives.defaultTags, tags);\n    }\n    clone() {\n        const copy = new Directives(this.yaml, this.tags);\n        copy.docStart = this.docStart;\n        return copy;\n    }\n    /**\n     * During parsing, get a Directives instance for the current document and\n     * update the stream state according to the current version's spec.\n     */\n    atDocument() {\n        const res = new Directives(this.yaml, this.tags);\n        switch (this.yaml.version) {\n            case '1.1':\n                this.atNextDocument = true;\n                break;\n            case '1.2':\n                this.atNextDocument = false;\n                this.yaml = {\n                    explicit: Directives.defaultYaml.explicit,\n                    version: '1.2'\n                };\n                this.tags = Object.assign({}, Directives.defaultTags);\n                break;\n        }\n        return res;\n    }\n    /**\n     * @param onError - May be called even if the action was successful\n     * @returns `true` on success\n     */\n    add(line, onError) {\n        if (this.atNextDocument) {\n            this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n            this.tags = Object.assign({}, Directives.defaultTags);\n            this.atNextDocument = false;\n        }\n        const parts = line.trim().split(/[ \\t]+/);\n        const name = parts.shift();\n        switch (name) {\n            case '%TAG': {\n                if (parts.length !== 2) {\n                    onError(0, '%TAG directive should contain exactly two parts');\n                    if (parts.length < 2)\n                        return false;\n                }\n                const [handle, prefix] = parts;\n                this.tags[handle] = prefix;\n                return true;\n            }\n            case '%YAML': {\n                this.yaml.explicit = true;\n                if (parts.length !== 1) {\n                    onError(0, '%YAML directive should contain exactly one part');\n                    return false;\n                }\n                const [version] = parts;\n                if (version === '1.1' || version === '1.2') {\n                    this.yaml.version = version;\n                    return true;\n                }\n                else {\n                    const isValid = /^\\d+\\.\\d+$/.test(version);\n                    onError(6, `Unsupported YAML version ${version}`, isValid);\n                    return false;\n                }\n            }\n            default:\n                onError(0, `Unknown directive ${name}`, true);\n                return false;\n        }\n    }\n    /**\n     * Resolves a tag, matching handles to those defined in %TAG directives.\n     *\n     * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n     *   `'!local'` tag, or `null` if unresolvable.\n     */\n    tagName(source, onError) {\n        if (source === '!')\n            return '!'; // non-specific tag\n        if (source[0] !== '!') {\n            onError(`Not a valid tag: ${source}`);\n            return null;\n        }\n        if (source[1] === '<') {\n            const verbatim = source.slice(2, -1);\n            if (verbatim === '!' || verbatim === '!!') {\n                onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n                return null;\n            }\n            if (source[source.length - 1] !== '>')\n                onError('Verbatim tags must end with a >');\n            return verbatim;\n        }\n        const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n        if (!suffix)\n            onError(`The ${source} tag has no suffix`);\n        const prefix = this.tags[handle];\n        if (prefix) {\n            try {\n                return prefix + decodeURIComponent(suffix);\n            }\n            catch (error) {\n                onError(String(error));\n                return null;\n            }\n        }\n        if (handle === '!')\n            return source; // local tag\n        onError(`Could not resolve tag: ${source}`);\n        return null;\n    }\n    /**\n     * Given a fully resolved tag, returns its printable string form,\n     * taking into account current tag prefixes and defaults.\n     */\n    tagString(tag) {\n        for (const [handle, prefix] of Object.entries(this.tags)) {\n            if (tag.startsWith(prefix))\n                return handle + escapeTagName(tag.substring(prefix.length));\n        }\n        return tag[0] === '!' ? tag : `!<${tag}>`;\n    }\n    toString(doc) {\n        const lines = this.yaml.explicit\n            ? [`%YAML ${this.yaml.version || '1.2'}`]\n            : [];\n        const tagEntries = Object.entries(this.tags);\n        let tagNames;\n        if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {\n            const tags = {};\n            visit.visit(doc.contents, (_key, node) => {\n                if (identity.isNode(node) && node.tag)\n                    tags[node.tag] = true;\n            });\n            tagNames = Object.keys(tags);\n        }\n        else\n            tagNames = [];\n        for (const [handle, prefix] of tagEntries) {\n            if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n                continue;\n            if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n                lines.push(`%TAG ${handle} ${prefix}`);\n        }\n        return lines.join('\\n');\n    }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexports.Directives = Directives;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n    if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n        const sa = JSON.stringify(anchor);\n        const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n        throw new Error(msg);\n    }\n    return true;\n}\nfunction anchorNames(root) {\n    const anchors = new Set();\n    visit.visit(root, {\n        Value(_key, node) {\n            if (node.anchor)\n                anchors.add(node.anchor);\n        }\n    });\n    return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n    for (let i = 1; true; ++i) {\n        const name = `${prefix}${i}`;\n        if (!exclude.has(name))\n            return name;\n    }\n}\nfunction createNodeAnchors(doc, prefix) {\n    const aliasObjects = [];\n    const sourceObjects = new Map();\n    let prevAnchors = null;\n    return {\n        onAnchor: (source) => {\n            aliasObjects.push(source);\n            prevAnchors ?? (prevAnchors = anchorNames(doc));\n            const anchor = findNewAnchor(prefix, prevAnchors);\n            prevAnchors.add(anchor);\n            return anchor;\n        },\n        /**\n         * With circular references, the source node is only resolved after all\n         * of its child nodes are. This is why anchors are set only after all of\n         * the nodes have been created.\n         */\n        setAnchors: () => {\n            for (const source of aliasObjects) {\n                const ref = sourceObjects.get(source);\n                if (typeof ref === 'object' &&\n                    ref.anchor &&\n                    (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {\n                    ref.node.anchor = ref.anchor;\n                }\n                else {\n                    const error = new Error('Failed to resolve repeated object (this should not happen)');\n                    error.source = source;\n                    throw error;\n                }\n            }\n        },\n        sourceObjects\n    };\n}\n\nexports.anchorIsValid = anchorIsValid;\nexports.anchorNames = anchorNames;\nexports.createNodeAnchors = createNodeAnchors;\nexports.findNewAnchor = findNewAnchor;\n","'use strict';\n\n/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n    if (val && typeof val === 'object') {\n        if (Array.isArray(val)) {\n            for (let i = 0, len = val.length; i < len; ++i) {\n                const v0 = val[i];\n                const v1 = applyReviver(reviver, val, String(i), v0);\n                // eslint-disable-next-line @typescript-eslint/no-array-delete\n                if (v1 === undefined)\n                    delete val[i];\n                else if (v1 !== v0)\n                    val[i] = v1;\n            }\n        }\n        else if (val instanceof Map) {\n            for (const k of Array.from(val.keys())) {\n                const v0 = val.get(k);\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    val.delete(k);\n                else if (v1 !== v0)\n                    val.set(k, v1);\n            }\n        }\n        else if (val instanceof Set) {\n            for (const v0 of Array.from(val)) {\n                const v1 = applyReviver(reviver, val, v0, v0);\n                if (v1 === undefined)\n                    val.delete(v0);\n                else if (v1 !== v0) {\n                    val.delete(v0);\n                    val.add(v1);\n                }\n            }\n        }\n        else {\n            for (const [k, v0] of Object.entries(val)) {\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    delete val[k];\n                else if (v1 !== v0)\n                    val[k] = v1;\n            }\n        }\n    }\n    return reviver.call(obj, key, val);\n}\n\nexports.applyReviver = applyReviver;\n","'use strict';\n\nvar identity = require('./identity.js');\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n *   as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n *   `{ keep: true }` is not set, output should be suitable for JSON\n *   stringification.\n */\nfunction toJS(value, arg, ctx) {\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n    if (Array.isArray(value))\n        return value.map((v, i) => toJS(v, String(i), ctx));\n    if (value && typeof value.toJSON === 'function') {\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n        if (!ctx || !identity.hasAnchor(value))\n            return value.toJSON(arg, ctx);\n        const data = { aliasCount: 0, count: 1, res: undefined };\n        ctx.anchors.set(value, data);\n        ctx.onCreate = res => {\n            data.res = res;\n            delete ctx.onCreate;\n        };\n        const res = value.toJSON(arg, ctx);\n        if (ctx.onCreate)\n            ctx.onCreate(res);\n        return res;\n    }\n    if (typeof value === 'bigint' && !ctx?.keep)\n        return Number(value);\n    return value;\n}\n\nexports.toJS = toJS;\n","'use strict';\n\nvar applyReviver = require('../doc/applyReviver.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nclass NodeBase {\n    constructor(type) {\n        Object.defineProperty(this, identity.NODE_TYPE, { value: type });\n    }\n    /** Create a copy of this node.  */\n    clone() {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** A plain JavaScript representation of this node. */\n    toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        if (!identity.isDocument(doc))\n            throw new TypeError('A document argument is required');\n        const ctx = {\n            anchors: new Map(),\n            doc,\n            keep: true,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS.toJS(this, '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n}\n\nexports.NodeBase = NodeBase;\n","'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar visit = require('../visit.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nclass Alias extends Node.NodeBase {\n    constructor(source) {\n        super(identity.ALIAS);\n        this.source = source;\n        Object.defineProperty(this, 'tag', {\n            set() {\n                throw new Error('Alias nodes cannot have tags');\n            }\n        });\n    }\n    /**\n     * Resolve the value of this alias within `doc`, finding the last\n     * instance of the `source` anchor before this node.\n     */\n    resolve(doc, ctx) {\n        if (ctx?.maxAliasCount === 0)\n            throw new ReferenceError('Alias resolution is disabled');\n        let nodes;\n        if (ctx?.aliasResolveCache) {\n            nodes = ctx.aliasResolveCache;\n        }\n        else {\n            nodes = [];\n            visit.visit(doc, {\n                Node: (_key, node) => {\n                    if (identity.isAlias(node) || identity.hasAnchor(node))\n                        nodes.push(node);\n                }\n            });\n            if (ctx)\n                ctx.aliasResolveCache = nodes;\n        }\n        let found = undefined;\n        for (const node of nodes) {\n            if (node === this)\n                break;\n            if (node.anchor === this.source)\n                found = node;\n        }\n        return found;\n    }\n    toJSON(_arg, ctx) {\n        if (!ctx)\n            return { source: this.source };\n        const { anchors, doc, maxAliasCount } = ctx;\n        const source = this.resolve(doc, ctx);\n        if (!source) {\n            const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n            throw new ReferenceError(msg);\n        }\n        let data = anchors.get(source);\n        if (!data) {\n            // Resolve anchors for Node.prototype.toJS()\n            toJS.toJS(source, null, ctx);\n            data = anchors.get(source);\n        }\n        /* istanbul ignore if */\n        if (data?.res === undefined) {\n            const msg = 'This should not happen: Alias anchor was not resolved?';\n            throw new ReferenceError(msg);\n        }\n        if (maxAliasCount >= 0) {\n            data.count += 1;\n            if (data.aliasCount === 0)\n                data.aliasCount = getAliasCount(doc, source, anchors);\n            if (data.count * data.aliasCount > maxAliasCount) {\n                const msg = 'Excessive alias count indicates a resource exhaustion attack';\n                throw new ReferenceError(msg);\n            }\n        }\n        return data.res;\n    }\n    toString(ctx, _onComment, _onChompKeep) {\n        const src = `*${this.source}`;\n        if (ctx) {\n            anchors.anchorIsValid(this.source);\n            if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n                const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n                throw new Error(msg);\n            }\n            if (ctx.implicitKey)\n                return `${src} `;\n        }\n        return src;\n    }\n}\nfunction getAliasCount(doc, node, anchors) {\n    if (identity.isAlias(node)) {\n        const source = node.resolve(doc);\n        const anchor = anchors && source && anchors.get(source);\n        return anchor ? anchor.count * anchor.aliasCount : 0;\n    }\n    else if (identity.isCollection(node)) {\n        let count = 0;\n        for (const item of node.items) {\n            const c = getAliasCount(doc, item, anchors);\n            if (c > count)\n                count = c;\n        }\n        return count;\n    }\n    else if (identity.isPair(node)) {\n        const kc = getAliasCount(doc, node.key, anchors);\n        const vc = getAliasCount(doc, node.value, anchors);\n        return Math.max(kc, vc);\n    }\n    return 1;\n}\n\nexports.Alias = Alias;\n","'use strict';\n\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends Node.NodeBase {\n    constructor(value) {\n        super(identity.SCALAR);\n        this.value = value;\n    }\n    toJSON(arg, ctx) {\n        return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);\n    }\n    toString() {\n        return String(this.value);\n    }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexports.Scalar = Scalar;\nexports.isScalarValue = isScalarValue;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n    if (tagName) {\n        const match = tags.filter(t => t.tag === tagName);\n        const tagObj = match.find(t => !t.format) ?? match[0];\n        if (!tagObj)\n            throw new Error(`Tag ${tagName} not found`);\n        return tagObj;\n    }\n    return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n    if (identity.isDocument(value))\n        value = value.contents;\n    if (identity.isNode(value))\n        return value;\n    if (identity.isPair(value)) {\n        const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);\n        map.items.push(value);\n        return map;\n    }\n    if (value instanceof String ||\n        value instanceof Number ||\n        value instanceof Boolean ||\n        (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n    ) {\n        // https://tc39.es/ecma262/#sec-serializejsonproperty\n        value = value.valueOf();\n    }\n    const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n    // Detect duplicate references to the same object & use Alias nodes for all\n    // after first. The `ref` wrapper allows for circular references to resolve.\n    let ref = undefined;\n    if (aliasDuplicateObjects && value && typeof value === 'object') {\n        ref = sourceObjects.get(value);\n        if (ref) {\n            ref.anchor ?? (ref.anchor = onAnchor(value));\n            return new Alias.Alias(ref.anchor);\n        }\n        else {\n            ref = { anchor: null, node: null };\n            sourceObjects.set(value, ref);\n        }\n    }\n    if (tagName?.startsWith('!!'))\n        tagName = defaultTagPrefix + tagName.slice(2);\n    let tagObj = findTagObject(value, tagName, schema.tags);\n    if (!tagObj) {\n        if (value && typeof value.toJSON === 'function') {\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n            value = value.toJSON();\n        }\n        if (!value || typeof value !== 'object') {\n            const node = new Scalar.Scalar(value);\n            if (ref)\n                ref.node = node;\n            return node;\n        }\n        tagObj =\n            value instanceof Map\n                ? schema[identity.MAP]\n                : Symbol.iterator in Object(value)\n                    ? schema[identity.SEQ]\n                    : schema[identity.MAP];\n    }\n    if (onTagObj) {\n        onTagObj(tagObj);\n        delete ctx.onTagObj;\n    }\n    const node = tagObj?.createNode\n        ? tagObj.createNode(ctx.schema, value, ctx)\n        : typeof tagObj?.nodeClass?.from === 'function'\n            ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n            : new Scalar.Scalar(value);\n    if (tagName)\n        node.tag = tagName;\n    else if (!tagObj.default)\n        node.tag = tagObj.tag;\n    if (ref)\n        ref.node = node;\n    return node;\n}\n\nexports.createNode = createNode;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\n\nfunction collectionFromPath(schema, path, value) {\n    let v = value;\n    for (let i = path.length - 1; i >= 0; --i) {\n        const k = path[i];\n        if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n            const a = [];\n            a[k] = v;\n            v = a;\n        }\n        else {\n            v = new Map([[k, v]]);\n        }\n    }\n    return createNode.createNode(v, undefined, {\n        aliasDuplicateObjects: false,\n        keepUndefined: false,\n        onAnchor: () => {\n            throw new Error('This should not happen, please report a bug.');\n        },\n        schema,\n        sourceObjects: new Map()\n    });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n    (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends Node.NodeBase {\n    constructor(type, schema) {\n        super(type);\n        Object.defineProperty(this, 'schema', {\n            value: schema,\n            configurable: true,\n            enumerable: false,\n            writable: true\n        });\n    }\n    /**\n     * Create a copy of this collection.\n     *\n     * @param schema - If defined, overwrites the original's schema\n     */\n    clone(schema) {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (schema)\n            copy.schema = schema;\n        copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /**\n     * Adds a value to the collection. For `!!map` and `!!omap` the value must\n     * be a Pair instance or a `{ key, value }` object, which may not have a key\n     * that already exists in the map.\n     */\n    addIn(path, value) {\n        if (isEmptyPath(path))\n            this.add(value);\n        else {\n            const [key, ...rest] = path;\n            const node = this.get(key, true);\n            if (identity.isCollection(node))\n                node.addIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n    /**\n     * Removes a value from the collection.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.delete(key);\n        const node = this.get(key, true);\n        if (identity.isCollection(node))\n            return node.deleteIn(rest);\n        else\n            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        const [key, ...rest] = path;\n        const node = this.get(key, true);\n        if (rest.length === 0)\n            return !keepScalar && identity.isScalar(node) ? node.value : node;\n        else\n            return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n    }\n    hasAllNullValues(allowScalar) {\n        return this.items.every(node => {\n            if (!identity.isPair(node))\n                return false;\n            const n = node.value;\n            return (n == null ||\n                (allowScalar &&\n                    identity.isScalar(n) &&\n                    n.value == null &&\n                    !n.commentBefore &&\n                    !n.comment &&\n                    !n.tag));\n        });\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     */\n    hasIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.has(key);\n        const node = this.get(key, true);\n        return identity.isCollection(node) ? node.hasIn(rest) : false;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        const [key, ...rest] = path;\n        if (rest.length === 0) {\n            this.set(key, value);\n        }\n        else {\n            const node = this.get(key, true);\n            if (identity.isCollection(node))\n                node.setIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n}\n\nexports.Collection = Collection;\nexports.collectionFromPath = collectionFromPath;\nexports.isEmptyPath = isEmptyPath;\n","'use strict';\n\n/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n    if (/^\\n+$/.test(comment))\n        return comment.substring(1);\n    return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n    ? indentComment(comment, indent)\n    : comment.includes('\\n')\n        ? '\\n' + indentComment(comment, indent)\n        : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexports.indentComment = indentComment;\nexports.lineComment = lineComment;\nexports.stringifyComment = stringifyComment;\n","'use strict';\n\nconst FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n    if (!lineWidth || lineWidth < 0)\n        return text;\n    if (lineWidth < minContentWidth)\n        minContentWidth = 0;\n    const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n    if (text.length <= endStep)\n        return text;\n    const folds = [];\n    const escapedFolds = {};\n    let end = lineWidth - indent.length;\n    if (typeof indentAtStart === 'number') {\n        if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n            folds.push(0);\n        else\n            end = lineWidth - indentAtStart;\n    }\n    let split = undefined;\n    let prev = undefined;\n    let overflow = false;\n    let i = -1;\n    let escStart = -1;\n    let escEnd = -1;\n    if (mode === FOLD_BLOCK) {\n        i = consumeMoreIndentedLines(text, i, indent.length);\n        if (i !== -1)\n            end = i + endStep;\n    }\n    for (let ch; (ch = text[(i += 1)]);) {\n        if (mode === FOLD_QUOTED && ch === '\\\\') {\n            escStart = i;\n            switch (text[i + 1]) {\n                case 'x':\n                    i += 3;\n                    break;\n                case 'u':\n                    i += 5;\n                    break;\n                case 'U':\n                    i += 9;\n                    break;\n                default:\n                    i += 1;\n            }\n            escEnd = i;\n        }\n        if (ch === '\\n') {\n            if (mode === FOLD_BLOCK)\n                i = consumeMoreIndentedLines(text, i, indent.length);\n            end = i + indent.length + endStep;\n            split = undefined;\n        }\n        else {\n            if (ch === ' ' &&\n                prev &&\n                prev !== ' ' &&\n                prev !== '\\n' &&\n                prev !== '\\t') {\n                // space surrounded by non-space can be replaced with newline + indent\n                const next = text[i + 1];\n                if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n                    split = i;\n            }\n            if (i >= end) {\n                if (split) {\n                    folds.push(split);\n                    end = split + endStep;\n                    split = undefined;\n                }\n                else if (mode === FOLD_QUOTED) {\n                    // white-space collected at end may stretch past lineWidth\n                    while (prev === ' ' || prev === '\\t') {\n                        prev = ch;\n                        ch = text[(i += 1)];\n                        overflow = true;\n                    }\n                    // Account for newline escape, but don't break preceding escape\n                    const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n                    // Bail out if lineWidth & minContentWidth are shorter than an escape string\n                    if (escapedFolds[j])\n                        return text;\n                    folds.push(j);\n                    escapedFolds[j] = true;\n                    end = j + endStep;\n                    split = undefined;\n                }\n                else {\n                    overflow = true;\n                }\n            }\n        }\n        prev = ch;\n    }\n    if (overflow && onOverflow)\n        onOverflow();\n    if (folds.length === 0)\n        return text;\n    if (onFold)\n        onFold();\n    let res = text.slice(0, folds[0]);\n    for (let i = 0; i < folds.length; ++i) {\n        const fold = folds[i];\n        const end = folds[i + 1] || text.length;\n        if (fold === 0)\n            res = `\\n${indent}${text.slice(0, end)}`;\n        else {\n            if (mode === FOLD_QUOTED && escapedFolds[fold])\n                res += `${text[fold]}\\\\`;\n            res += `\\n${indent}${text.slice(fold + 1, end)}`;\n        }\n    }\n    return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n    let end = i;\n    let start = i + 1;\n    let ch = text[start];\n    while (ch === ' ' || ch === '\\t') {\n        if (i < start + indent) {\n            ch = text[++i];\n        }\n        else {\n            do {\n                ch = text[++i];\n            } while (ch && ch !== '\\n');\n            end = i;\n            start = i + 1;\n            ch = text[start];\n        }\n    }\n    return end;\n}\n\nexports.FOLD_BLOCK = FOLD_BLOCK;\nexports.FOLD_FLOW = FOLD_FLOW;\nexports.FOLD_QUOTED = FOLD_QUOTED;\nexports.foldFlowLines = foldFlowLines;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar foldFlowLines = require('./foldFlowLines.js');\n\nconst getFoldOptions = (ctx, isBlock) => ({\n    indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n    lineWidth: ctx.options.lineWidth,\n    minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n    if (!lineWidth || lineWidth < 0)\n        return false;\n    const limit = lineWidth - indentLength;\n    const strLen = str.length;\n    if (strLen <= limit)\n        return false;\n    for (let i = 0, start = 0; i < strLen; ++i) {\n        if (str[i] === '\\n') {\n            if (i - start > limit)\n                return true;\n            start = i + 1;\n            if (strLen - start <= limit)\n                return false;\n        }\n    }\n    return true;\n}\nfunction doubleQuotedString(value, ctx) {\n    const json = JSON.stringify(value);\n    if (ctx.options.doubleQuotedAsJSON)\n        return json;\n    const { implicitKey } = ctx;\n    const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    let str = '';\n    let start = 0;\n    for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n        if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n            // space before newline needs to be escaped to not be folded\n            str += json.slice(start, i) + '\\\\ ';\n            i += 1;\n            start = i;\n            ch = '\\\\';\n        }\n        if (ch === '\\\\')\n            switch (json[i + 1]) {\n                case 'u':\n                    {\n                        str += json.slice(start, i);\n                        const code = json.substr(i + 2, 4);\n                        switch (code) {\n                            case '0000':\n                                str += '\\\\0';\n                                break;\n                            case '0007':\n                                str += '\\\\a';\n                                break;\n                            case '000b':\n                                str += '\\\\v';\n                                break;\n                            case '001b':\n                                str += '\\\\e';\n                                break;\n                            case '0085':\n                                str += '\\\\N';\n                                break;\n                            case '00a0':\n                                str += '\\\\_';\n                                break;\n                            case '2028':\n                                str += '\\\\L';\n                                break;\n                            case '2029':\n                                str += '\\\\P';\n                                break;\n                            default:\n                                if (code.substr(0, 2) === '00')\n                                    str += '\\\\x' + code.substr(2);\n                                else\n                                    str += json.substr(i, 6);\n                        }\n                        i += 5;\n                        start = i + 1;\n                    }\n                    break;\n                case 'n':\n                    if (implicitKey ||\n                        json[i + 2] === '\"' ||\n                        json.length < minMultiLineLength) {\n                        i += 1;\n                    }\n                    else {\n                        // folding will eat first newline\n                        str += json.slice(start, i) + '\\n\\n';\n                        while (json[i + 2] === '\\\\' &&\n                            json[i + 3] === 'n' &&\n                            json[i + 4] !== '\"') {\n                            str += '\\n';\n                            i += 2;\n                        }\n                        str += indent;\n                        // space after newline needs to be escaped to not be folded\n                        if (json[i + 2] === ' ')\n                            str += '\\\\';\n                        i += 1;\n                        start = i + 1;\n                    }\n                    break;\n                default:\n                    i += 1;\n            }\n    }\n    str = start ? str + json.slice(start) : json;\n    return implicitKey\n        ? str\n        : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n    if (ctx.options.singleQuote === false ||\n        (ctx.implicitKey && value.includes('\\n')) ||\n        /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n    )\n        return doubleQuotedString(value, ctx);\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n    return ctx.implicitKey\n        ? res\n        : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n    const { singleQuote } = ctx.options;\n    let qs;\n    if (singleQuote === false)\n        qs = doubleQuotedString;\n    else {\n        const hasDouble = value.includes('\"');\n        const hasSingle = value.includes(\"'\");\n        if (hasDouble && !hasSingle)\n            qs = singleQuotedString;\n        else if (hasSingle && !hasDouble)\n            qs = doubleQuotedString;\n        else\n            qs = singleQuote ? singleQuotedString : doubleQuotedString;\n    }\n    return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n    blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n    blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n    const { blockQuote, commentString, lineWidth } = ctx.options;\n    // 1. Block can't end in whitespace unless the last line is non-empty.\n    // 2. Strings consisting of only whitespace are best rendered explicitly.\n    if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n        return quotedString(value, ctx);\n    }\n    const indent = ctx.indent ||\n        (ctx.forceBlockIndent || containsDocumentMarker(value) ? '  ' : '');\n    const literal = blockQuote === 'literal'\n        ? true\n        : blockQuote === 'folded' || type === Scalar.Scalar.BLOCK_FOLDED\n            ? false\n            : type === Scalar.Scalar.BLOCK_LITERAL\n                ? true\n                : !lineLengthOverLimit(value, lineWidth, indent.length);\n    if (!value)\n        return literal ? '|\\n' : '>\\n';\n    // determine chomping from whitespace at value end\n    let chomp;\n    let endStart;\n    for (endStart = value.length; endStart > 0; --endStart) {\n        const ch = value[endStart - 1];\n        if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n            break;\n    }\n    let end = value.substring(endStart);\n    const endNlPos = end.indexOf('\\n');\n    if (endNlPos === -1) {\n        chomp = '-'; // strip\n    }\n    else if (value === end || endNlPos !== end.length - 1) {\n        chomp = '+'; // keep\n        if (onChompKeep)\n            onChompKeep();\n    }\n    else {\n        chomp = ''; // clip\n    }\n    if (end) {\n        value = value.slice(0, -end.length);\n        if (end[end.length - 1] === '\\n')\n            end = end.slice(0, -1);\n        end = end.replace(blockEndNewlines, `$&${indent}`);\n    }\n    // determine indent indicator from whitespace at value start\n    let startWithSpace = false;\n    let startEnd;\n    let startNlPos = -1;\n    for (startEnd = 0; startEnd < value.length; ++startEnd) {\n        const ch = value[startEnd];\n        if (ch === ' ')\n            startWithSpace = true;\n        else if (ch === '\\n')\n            startNlPos = startEnd;\n        else\n            break;\n    }\n    let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n    if (start) {\n        value = value.substring(start.length);\n        start = start.replace(/\\n+/g, `$&${indent}`);\n    }\n    const indentSize = indent ? '2' : '1'; // root is at -1\n    // Leading | or > is added later\n    let header = (startWithSpace ? indentSize : '') + chomp;\n    if (comment) {\n        header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n        if (onComment)\n            onComment();\n    }\n    if (!literal) {\n        const foldedValue = value\n            .replace(/\\n+/g, '\\n$&')\n            .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n            //                ^ more-ind. ^ empty     ^ capture next empty lines only at end of indent\n            .replace(/\\n+/g, `$&${indent}`);\n        let literalFallback = false;\n        const foldOptions = getFoldOptions(ctx, true);\n        if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) {\n            foldOptions.onOverflow = () => {\n                literalFallback = true;\n            };\n        }\n        const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);\n        if (!literalFallback)\n            return `>${header}\\n${indent}${body}`;\n    }\n    value = value.replace(/\\n+/g, `$&${indent}`);\n    return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n    const { type, value } = item;\n    const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n    if ((implicitKey && value.includes('\\n')) ||\n        (inFlow && /[[\\]{},]/.test(value))) {\n        return quotedString(value, ctx);\n    }\n    if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n        // not allowed:\n        // - '-' or '?'\n        // - start with an indicator character (except [?:-]) or /[?-] /\n        // - '\\n ', ': ' or ' \\n' anywhere\n        // - '#' not preceded by a non-space char\n        // - end with ' ' or ':'\n        return implicitKey || inFlow || !value.includes('\\n')\n            ? quotedString(value, ctx)\n            : blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (!implicitKey &&\n        !inFlow &&\n        type !== Scalar.Scalar.PLAIN &&\n        value.includes('\\n')) {\n        // Where allowed & type not set explicitly, prefer block style for multiline strings\n        return blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (containsDocumentMarker(value)) {\n        if (indent === '') {\n            ctx.forceBlockIndent = true;\n            return blockString(item, ctx, onComment, onChompKeep);\n        }\n        else if (implicitKey && indent === indentStep) {\n            return quotedString(value, ctx);\n        }\n    }\n    const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n    // Verify that output will be parsed as a string, as e.g. plain numbers and\n    // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n    // and others in v1.1.\n    if (actualString) {\n        const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n        const { compat, tags } = ctx.doc.schema;\n        if (tags.some(test) || compat?.some(test))\n            return quotedString(value, ctx);\n    }\n    return implicitKey\n        ? str\n        : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n    const { implicitKey, inFlow } = ctx;\n    const ss = typeof item.value === 'string'\n        ? item\n        : Object.assign({}, item, { value: String(item.value) });\n    let { type } = item;\n    if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n        // force double quotes on control characters & unpaired surrogates\n        if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n            type = Scalar.Scalar.QUOTE_DOUBLE;\n    }\n    const _stringify = (_type) => {\n        switch (_type) {\n            case Scalar.Scalar.BLOCK_FOLDED:\n            case Scalar.Scalar.BLOCK_LITERAL:\n                return implicitKey || inFlow\n                    ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n                    : blockString(ss, ctx, onComment, onChompKeep);\n            case Scalar.Scalar.QUOTE_DOUBLE:\n                return doubleQuotedString(ss.value, ctx);\n            case Scalar.Scalar.QUOTE_SINGLE:\n                return singleQuotedString(ss.value, ctx);\n            case Scalar.Scalar.PLAIN:\n                return plainString(ss, ctx, onComment, onChompKeep);\n            default:\n                return null;\n        }\n    };\n    let res = _stringify(type);\n    if (res === null) {\n        const { defaultKeyType, defaultStringType } = ctx.options;\n        const t = (implicitKey && defaultKeyType) || defaultStringType;\n        res = _stringify(t);\n        if (res === null)\n            throw new Error(`Unsupported default string type ${t}`);\n    }\n    return res;\n}\n\nexports.stringifyString = stringifyString;\n","'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar identity = require('../nodes/identity.js');\nvar stringifyComment = require('./stringifyComment.js');\nvar stringifyString = require('./stringifyString.js');\n\nfunction createStringifyContext(doc, options) {\n    const opt = Object.assign({\n        blockQuote: true,\n        commentString: stringifyComment.stringifyComment,\n        defaultKeyType: null,\n        defaultStringType: 'PLAIN',\n        directives: null,\n        doubleQuotedAsJSON: false,\n        doubleQuotedMinMultiLineLength: 40,\n        falseStr: 'false',\n        flowCollectionPadding: true,\n        indentSeq: true,\n        lineWidth: 80,\n        minContentWidth: 20,\n        nullStr: 'null',\n        simpleKeys: false,\n        singleQuote: null,\n        trailingComma: false,\n        trueStr: 'true',\n        verifyAliasOrder: true\n    }, doc.schema.toStringOptions, options);\n    let inFlow;\n    switch (opt.collectionStyle) {\n        case 'block':\n            inFlow = false;\n            break;\n        case 'flow':\n            inFlow = true;\n            break;\n        default:\n            inFlow = null;\n    }\n    return {\n        anchors: new Set(),\n        doc,\n        flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n        indent: '',\n        indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : '  ',\n        inFlow,\n        options: opt\n    };\n}\nfunction getTagObject(tags, item) {\n    if (item.tag) {\n        const match = tags.filter(t => t.tag === item.tag);\n        if (match.length > 0)\n            return match.find(t => t.format === item.format) ?? match[0];\n    }\n    let tagObj = undefined;\n    let obj;\n    if (identity.isScalar(item)) {\n        obj = item.value;\n        let match = tags.filter(t => t.identify?.(obj));\n        if (match.length > 1) {\n            const testMatch = match.filter(t => t.test);\n            if (testMatch.length > 0)\n                match = testMatch;\n        }\n        tagObj =\n            match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n    }\n    else {\n        obj = item;\n        tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n    }\n    if (!tagObj) {\n        const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n        throw new Error(`Tag not resolved for ${name} value`);\n    }\n    return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {\n    if (!doc.directives)\n        return '';\n    const props = [];\n    const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;\n    if (anchor && anchors.anchorIsValid(anchor)) {\n        anchors$1.add(anchor);\n        props.push(`&${anchor}`);\n    }\n    const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n    if (tag)\n        props.push(doc.directives.tagString(tag));\n    return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n    if (identity.isPair(item))\n        return item.toString(ctx, onComment, onChompKeep);\n    if (identity.isAlias(item)) {\n        if (ctx.doc.directives)\n            return item.toString(ctx);\n        if (ctx.resolvedAliases?.has(item)) {\n            throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n        }\n        else {\n            if (ctx.resolvedAliases)\n                ctx.resolvedAliases.add(item);\n            else\n                ctx.resolvedAliases = new Set([item]);\n            item = item.resolve(ctx.doc);\n        }\n    }\n    let tagObj = undefined;\n    const node = identity.isNode(item)\n        ? item\n        : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n    tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n    const props = stringifyProps(node, tagObj, ctx);\n    if (props.length > 0)\n        ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n    const str = typeof tagObj.stringify === 'function'\n        ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n        : identity.isScalar(node)\n            ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)\n            : node.toString(ctx, onComment, onChompKeep);\n    if (!props)\n        return str;\n    return identity.isScalar(node) || str[0] === '{' || str[0] === '['\n        ? `${props} ${str}`\n        : `${props}\\n${ctx.indent}${str}`;\n}\n\nexports.createStringifyContext = createStringifyContext;\nexports.stringify = stringify;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n    const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n    let keyComment = (identity.isNode(key) && key.comment) || null;\n    if (simpleKeys) {\n        if (keyComment) {\n            throw new Error('With simple keys, key nodes cannot have comments');\n        }\n        if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) {\n            const msg = 'With simple keys, collection cannot be used as a key value';\n            throw new Error(msg);\n        }\n    }\n    let explicitKey = !simpleKeys &&\n        (!key ||\n            (keyComment && value == null && !ctx.inFlow) ||\n            identity.isCollection(key) ||\n            (identity.isScalar(key)\n                ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL\n                : typeof key === 'object'));\n    ctx = Object.assign({}, ctx, {\n        allNullValues: false,\n        implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n        indent: indent + indentStep\n    });\n    let keyCommentDone = false;\n    let chompKeep = false;\n    let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n    if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n        if (simpleKeys)\n            throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n        explicitKey = true;\n    }\n    if (ctx.inFlow) {\n        if (allNullValues || value == null) {\n            if (keyCommentDone && onComment)\n                onComment();\n            return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n        }\n    }\n    else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n        str = `? ${str}`;\n        if (keyComment && !keyCommentDone) {\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n        }\n        else if (chompKeep && onChompKeep)\n            onChompKeep();\n        return str;\n    }\n    if (keyCommentDone)\n        keyComment = null;\n    if (explicitKey) {\n        if (keyComment)\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n        str = `? ${str}\\n${indent}:`;\n    }\n    else {\n        str = `${str}:`;\n        if (keyComment)\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n    }\n    let vsb, vcb, valueComment;\n    if (identity.isNode(value)) {\n        vsb = !!value.spaceBefore;\n        vcb = value.commentBefore;\n        valueComment = value.comment;\n    }\n    else {\n        vsb = false;\n        vcb = null;\n        valueComment = null;\n        if (value && typeof value === 'object')\n            value = doc.createNode(value);\n    }\n    ctx.implicitKey = false;\n    if (!explicitKey && !keyComment && identity.isScalar(value))\n        ctx.indentAtStart = str.length + 1;\n    chompKeep = false;\n    if (!indentSeq &&\n        indentStep.length >= 2 &&\n        !ctx.inFlow &&\n        !explicitKey &&\n        identity.isSeq(value) &&\n        !value.flow &&\n        !value.tag &&\n        !value.anchor) {\n        // If indentSeq === false, consider '- ' as part of indentation where possible\n        ctx.indent = ctx.indent.substring(2);\n    }\n    let valueCommentDone = false;\n    const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n    let ws = ' ';\n    if (keyComment || vsb || vcb) {\n        ws = vsb ? '\\n' : '';\n        if (vcb) {\n            const cs = commentString(vcb);\n            ws += `\\n${stringifyComment.indentComment(cs, ctx.indent)}`;\n        }\n        if (valueStr === '' && !ctx.inFlow) {\n            if (ws === '\\n' && valueComment)\n                ws = '\\n\\n';\n        }\n        else {\n            ws += `\\n${ctx.indent}`;\n        }\n    }\n    else if (!explicitKey && identity.isCollection(value)) {\n        const vs0 = valueStr[0];\n        const nl0 = valueStr.indexOf('\\n');\n        const hasNewline = nl0 !== -1;\n        const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n        if (hasNewline || !flow) {\n            let hasPropsLine = false;\n            if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n                let sp0 = valueStr.indexOf(' ');\n                if (vs0 === '&' &&\n                    sp0 !== -1 &&\n                    sp0 < nl0 &&\n                    valueStr[sp0 + 1] === '!') {\n                    sp0 = valueStr.indexOf(' ', sp0 + 1);\n                }\n                if (sp0 === -1 || nl0 < sp0)\n                    hasPropsLine = true;\n            }\n            if (!hasPropsLine)\n                ws = `\\n${ctx.indent}`;\n        }\n    }\n    else if (valueStr === '' || valueStr[0] === '\\n') {\n        ws = '';\n    }\n    str += ws + valueStr;\n    if (ctx.inFlow) {\n        if (valueCommentDone && onComment)\n            onComment();\n    }\n    else if (valueComment && !valueCommentDone) {\n        str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));\n    }\n    else if (chompKeep && onChompKeep) {\n        onChompKeep();\n    }\n    return str;\n}\n\nexports.stringifyPair = stringifyPair;\n","'use strict';\n\nvar node_process = require('process');\n\nfunction debug(logLevel, ...messages) {\n    if (logLevel === 'debug')\n        console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n    if (logLevel === 'debug' || logLevel === 'warn') {\n        if (typeof node_process.emitWarning === 'function')\n            node_process.emitWarning(warning);\n        else\n            console.warn(warning);\n    }\n}\n\nexports.debug = debug;\nexports.warn = warn;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Scalar = require('../../nodes/Scalar.js');\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n    identify: value => value === MERGE_KEY ||\n        (typeof value === 'symbol' && value.description === MERGE_KEY),\n    default: 'key',\n    tag: 'tag:yaml.org,2002:merge',\n    test: /^<<$/,\n    resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {\n        addToJSMap: addMergeToJSMap\n    }),\n    stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n    (identity.isScalar(key) &&\n        (!key.type || key.type === Scalar.Scalar.PLAIN) &&\n        merge.identify(key.value))) &&\n    ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (identity.isSeq(source))\n        for (const it of source.items)\n            mergeValue(ctx, map, it);\n    else if (Array.isArray(source))\n        for (const it of source)\n            mergeValue(ctx, map, it);\n    else\n        mergeValue(ctx, map, source);\n}\nfunction mergeValue(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (!identity.isMap(source))\n        throw new Error('Merge sources must be maps or map aliases');\n    const srcMap = source.toJSON(null, ctx, Map);\n    for (const [key, value] of srcMap) {\n        if (map instanceof Map) {\n            if (!map.has(key))\n                map.set(key, value);\n        }\n        else if (map instanceof Set) {\n            map.add(key);\n        }\n        else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n            Object.defineProperty(map, key, {\n                value,\n                writable: true,\n                enumerable: true,\n                configurable: true\n            });\n        }\n    }\n    return map;\n}\nfunction resolveAliasValue(ctx, value) {\n    return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value;\n}\n\nexports.addMergeToJSMap = addMergeToJSMap;\nexports.isMergeKey = isMergeKey;\nexports.merge = merge;\n","'use strict';\n\nvar log = require('../log.js');\nvar merge = require('../schema/yaml-1.1/merge.js');\nvar stringify = require('../stringify/stringify.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n    if (identity.isNode(key) && key.addToJSMap)\n        key.addToJSMap(ctx, map, value);\n    // TODO: Should drop this special case for bare << handling\n    else if (merge.isMergeKey(ctx, key))\n        merge.addMergeToJSMap(ctx, map, value);\n    else {\n        const jsKey = toJS.toJS(key, '', ctx);\n        if (map instanceof Map) {\n            map.set(jsKey, toJS.toJS(value, jsKey, ctx));\n        }\n        else if (map instanceof Set) {\n            map.add(jsKey);\n        }\n        else {\n            const stringKey = stringifyKey(key, jsKey, ctx);\n            const jsValue = toJS.toJS(value, stringKey, ctx);\n            if (stringKey in map)\n                Object.defineProperty(map, stringKey, {\n                    value: jsValue,\n                    writable: true,\n                    enumerable: true,\n                    configurable: true\n                });\n            else\n                map[stringKey] = jsValue;\n        }\n    }\n    return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n    if (jsKey === null)\n        return '';\n    // eslint-disable-next-line @typescript-eslint/no-base-to-string\n    if (typeof jsKey !== 'object')\n        return String(jsKey);\n    if (identity.isNode(key) && ctx?.doc) {\n        const strCtx = stringify.createStringifyContext(ctx.doc, {});\n        strCtx.anchors = new Set();\n        for (const node of ctx.anchors.keys())\n            strCtx.anchors.add(node.anchor);\n        strCtx.inFlow = true;\n        strCtx.inStringifyKey = true;\n        const strKey = key.toString(strCtx);\n        if (!ctx.mapKeyWarned) {\n            let jsonStr = JSON.stringify(strKey);\n            if (jsonStr.length > 40)\n                jsonStr = jsonStr.substring(0, 36) + '...\"';\n            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.`);\n            ctx.mapKeyWarned = true;\n        }\n        return strKey;\n    }\n    return JSON.stringify(jsKey);\n}\n\nexports.addPairToJSMap = addPairToJSMap;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyPair = require('../stringify/stringifyPair.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar identity = require('./identity.js');\n\nfunction createPair(key, value, ctx) {\n    const k = createNode.createNode(key, undefined, ctx);\n    const v = createNode.createNode(value, undefined, ctx);\n    return new Pair(k, v);\n}\nclass Pair {\n    constructor(key, value = null) {\n        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });\n        this.key = key;\n        this.value = value;\n    }\n    clone(schema) {\n        let { key, value } = this;\n        if (identity.isNode(key))\n            key = key.clone(schema);\n        if (identity.isNode(value))\n            value = value.clone(schema);\n        return new Pair(key, value);\n    }\n    toJSON(_, ctx) {\n        const pair = ctx?.mapAsMap ? new Map() : {};\n        return addPairToJSMap.addPairToJSMap(ctx, pair, this);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        return ctx?.doc\n            ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)\n            : JSON.stringify(this);\n    }\n}\n\nexports.Pair = Pair;\nexports.createPair = createPair;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyCollection(collection, ctx, options) {\n    const flow = ctx.inFlow ?? collection.flow;\n    const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n    return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n    const { indent, options: { commentString } } = ctx;\n    const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n    let chompKeep = false; // flag for the preceding node's status\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (identity.isNode(item)) {\n            if (!chompKeep && item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (identity.isPair(item)) {\n            const ik = identity.isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (!chompKeep && ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n            }\n        }\n        chompKeep = false;\n        let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n        if (comment)\n            str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n        if (chompKeep && comment)\n            chompKeep = false;\n        lines.push(blockItemPrefix + str);\n    }\n    let str;\n    if (lines.length === 0) {\n        str = flowChars.start + flowChars.end;\n    }\n    else {\n        str = lines[0];\n        for (let i = 1; i < lines.length; ++i) {\n            const line = lines[i];\n            str += line ? `\\n${indent}${line}` : '\\n';\n        }\n    }\n    if (comment) {\n        str += '\\n' + stringifyComment.indentComment(commentString(comment), indent);\n        if (onComment)\n            onComment();\n    }\n    else if (chompKeep && onChompKeep)\n        onChompKeep();\n    return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n    const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n    itemIndent += indentStep;\n    const itemCtx = Object.assign({}, ctx, {\n        indent: itemIndent,\n        inFlow: true,\n        type: null\n    });\n    let reqNewline = false;\n    let linesAtValue = 0;\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (identity.isNode(item)) {\n            if (item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, false);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (identity.isPair(item)) {\n            const ik = identity.isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, false);\n                if (ik.comment)\n                    reqNewline = true;\n            }\n            const iv = identity.isNode(item.value) ? item.value : null;\n            if (iv) {\n                if (iv.comment)\n                    comment = iv.comment;\n                if (iv.commentBefore)\n                    reqNewline = true;\n            }\n            else if (item.value == null && ik?.comment) {\n                comment = ik.comment;\n            }\n        }\n        if (comment)\n            reqNewline = true;\n        let str = stringify.stringify(item, itemCtx, () => (comment = null));\n        reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\\n'));\n        if (i < items.length - 1) {\n            str += ',';\n        }\n        else if (ctx.options.trailingComma) {\n            if (ctx.options.lineWidth > 0) {\n                reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +\n                    (str.length + 2) >\n                    ctx.options.lineWidth);\n            }\n            if (reqNewline) {\n                str += ',';\n            }\n        }\n        if (comment)\n            str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n        lines.push(str);\n        linesAtValue = lines.length;\n    }\n    const { start, end } = flowChars;\n    if (lines.length === 0) {\n        return start + end;\n    }\n    else {\n        if (!reqNewline) {\n            const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n            reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n        }\n        if (reqNewline) {\n            let str = start;\n            for (const line of lines)\n                str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n            return `${str}\\n${indent}${end}`;\n        }\n        else {\n            return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n        }\n    }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n    if (comment && chompKeep)\n        comment = comment.replace(/^\\n+/, '');\n    if (comment) {\n        const ic = stringifyComment.indentComment(commentString(comment), indent);\n        lines.push(ic.trimStart()); // Avoid double indent on first line\n    }\n}\n\nexports.stringifyCollection = stringifyCollection;\n","'use strict';\n\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Pair = require('./Pair.js');\nvar Scalar = require('./Scalar.js');\n\nfunction findPair(items, key) {\n    const k = identity.isScalar(key) ? key.value : key;\n    for (const it of items) {\n        if (identity.isPair(it)) {\n            if (it.key === key || it.key === k)\n                return it;\n            if (identity.isScalar(it.key) && it.key.value === k)\n                return it;\n        }\n    }\n    return undefined;\n}\nclass YAMLMap extends Collection.Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:map';\n    }\n    constructor(schema) {\n        super(identity.MAP, schema);\n        this.items = [];\n    }\n    /**\n     * A generic collection parsing method that can be extended\n     * to other node classes that inherit from YAMLMap\n     */\n    static from(schema, obj, ctx) {\n        const { keepUndefined, replacer } = ctx;\n        const map = new this(schema);\n        const add = (key, value) => {\n            if (typeof replacer === 'function')\n                value = replacer.call(obj, key, value);\n            else if (Array.isArray(replacer) && !replacer.includes(key))\n                return;\n            if (value !== undefined || keepUndefined)\n                map.items.push(Pair.createPair(key, value, ctx));\n        };\n        if (obj instanceof Map) {\n            for (const [key, value] of obj)\n                add(key, value);\n        }\n        else if (obj && typeof obj === 'object') {\n            for (const key of Object.keys(obj))\n                add(key, obj[key]);\n        }\n        if (typeof schema.sortMapEntries === 'function') {\n            map.items.sort(schema.sortMapEntries);\n        }\n        return map;\n    }\n    /**\n     * Adds a value to the collection.\n     *\n     * @param overwrite - If not set `true`, using a key that is already in the\n     *   collection will throw. Otherwise, overwrites the previous value.\n     */\n    add(pair, overwrite) {\n        let _pair;\n        if (identity.isPair(pair))\n            _pair = pair;\n        else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n            // In TypeScript, this never happens.\n            _pair = new Pair.Pair(pair, pair?.value);\n        }\n        else\n            _pair = new Pair.Pair(pair.key, pair.value);\n        const prev = findPair(this.items, _pair.key);\n        const sortEntries = this.schema?.sortMapEntries;\n        if (prev) {\n            if (!overwrite)\n                throw new Error(`Key ${_pair.key} already set`);\n            // For scalars, keep the old node & its comments and anchors\n            if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))\n                prev.value.value = _pair.value;\n            else\n                prev.value = _pair.value;\n        }\n        else if (sortEntries) {\n            const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n            if (i === -1)\n                this.items.push(_pair);\n            else\n                this.items.splice(i, 0, _pair);\n        }\n        else {\n            this.items.push(_pair);\n        }\n    }\n    delete(key) {\n        const it = findPair(this.items, key);\n        if (!it)\n            return false;\n        const del = this.items.splice(this.items.indexOf(it), 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const it = findPair(this.items, key);\n        const node = it?.value;\n        return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;\n    }\n    has(key) {\n        return !!findPair(this.items, key);\n    }\n    set(key, value) {\n        this.add(new Pair.Pair(key, value), true);\n    }\n    /**\n     * @param ctx - Conversion context, originally set in Document#toJS()\n     * @param {Class} Type - If set, forces the returned collection type\n     * @returns Instance of Type, Map, or Object\n     */\n    toJSON(_, ctx, Type) {\n        const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const item of this.items)\n            addPairToJSMap.addPairToJSMap(ctx, map, item);\n        return map;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        for (const item of this.items) {\n            if (!identity.isPair(item))\n                throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n        }\n        if (!ctx.allNullValues && this.hasAllNullValues(false))\n            ctx = Object.assign({}, ctx, { allNullValues: true });\n        return stringifyCollection.stringifyCollection(this, ctx, {\n            blockItemPrefix: '',\n            flowChars: { start: '{', end: '}' },\n            itemIndent: ctx.indent || '',\n            onChompKeep,\n            onComment\n        });\n    }\n}\n\nexports.YAMLMap = YAMLMap;\nexports.findPair = findPair;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nconst map = {\n    collection: 'map',\n    default: true,\n    nodeClass: YAMLMap.YAMLMap,\n    tag: 'tag:yaml.org,2002:map',\n    resolve(map, onError) {\n        if (!identity.isMap(map))\n            onError('Expected a mapping for this tag');\n        return map;\n    },\n    createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)\n};\n\nexports.map = map;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Scalar = require('./Scalar.js');\nvar toJS = require('./toJS.js');\n\nclass YAMLSeq extends Collection.Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:seq';\n    }\n    constructor(schema) {\n        super(identity.SEQ, schema);\n        this.items = [];\n    }\n    add(value) {\n        this.items.push(value);\n    }\n    /**\n     * Removes a value from the collection.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     *\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return false;\n        const del = this.items.splice(idx, 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return undefined;\n        const it = this.items[idx];\n        return !keepScalar && identity.isScalar(it) ? it.value : it;\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     */\n    has(key) {\n        const idx = asItemIndex(key);\n        return typeof idx === 'number' && idx < this.items.length;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     *\n     * If `key` does not contain a representation of an integer, this will throw.\n     * It may be wrapped in a `Scalar`.\n     */\n    set(key, value) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            throw new Error(`Expected a valid index, not ${key}.`);\n        const prev = this.items[idx];\n        if (identity.isScalar(prev) && Scalar.isScalarValue(value))\n            prev.value = value;\n        else\n            this.items[idx] = value;\n    }\n    toJSON(_, ctx) {\n        const seq = [];\n        if (ctx?.onCreate)\n            ctx.onCreate(seq);\n        let i = 0;\n        for (const item of this.items)\n            seq.push(toJS.toJS(item, String(i++), ctx));\n        return seq;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        return stringifyCollection.stringifyCollection(this, ctx, {\n            blockItemPrefix: '- ',\n            flowChars: { start: '[', end: ']' },\n            itemIndent: (ctx.indent || '') + '  ',\n            onChompKeep,\n            onComment\n        });\n    }\n    static from(schema, obj, ctx) {\n        const { replacer } = ctx;\n        const seq = new this(schema);\n        if (obj && Symbol.iterator in Object(obj)) {\n            let i = 0;\n            for (let it of obj) {\n                if (typeof replacer === 'function') {\n                    const key = obj instanceof Set ? it : String(i++);\n                    it = replacer.call(obj, key, it);\n                }\n                seq.items.push(createNode.createNode(it, undefined, ctx));\n            }\n        }\n        return seq;\n    }\n}\nfunction asItemIndex(key) {\n    let idx = identity.isScalar(key) ? key.value : key;\n    if (idx && typeof idx === 'string')\n        idx = Number(idx);\n    return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n        ? idx\n        : null;\n}\n\nexports.YAMLSeq = YAMLSeq;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nconst seq = {\n    collection: 'seq',\n    default: true,\n    nodeClass: YAMLSeq.YAMLSeq,\n    tag: 'tag:yaml.org,2002:seq',\n    resolve(seq, onError) {\n        if (!identity.isSeq(seq))\n            onError('Expected a sequence for this tag');\n        return seq;\n    },\n    createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)\n};\n\nexports.seq = seq;\n","'use strict';\n\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst string = {\n    identify: value => typeof value === 'string',\n    default: true,\n    tag: 'tag:yaml.org,2002:str',\n    resolve: str => str,\n    stringify(item, ctx, onComment, onChompKeep) {\n        ctx = Object.assign({ actualString: true }, ctx);\n        return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);\n    }\n};\n\nexports.string = string;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst nullTag = {\n    identify: value => value == null,\n    createNode: () => new Scalar.Scalar(null),\n    default: true,\n    tag: 'tag:yaml.org,2002:null',\n    test: /^(?:~|[Nn]ull|NULL)?$/,\n    resolve: () => new Scalar.Scalar(null),\n    stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n        ? source\n        : ctx.options.nullStr\n};\n\nexports.nullTag = nullTag;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst boolTag = {\n    identify: value => typeof value === 'boolean',\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n    resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),\n    stringify({ source, value }, ctx) {\n        if (source && boolTag.test.test(source)) {\n            const sv = source[0] === 't' || source[0] === 'T';\n            if (value === sv)\n                return source;\n        }\n        return value ? ctx.options.trueStr : ctx.options.falseStr;\n    }\n};\n\nexports.boolTag = boolTag;\n","'use strict';\n\nfunction stringifyNumber({ format, minFractionDigits, tag, value }) {\n    if (typeof value === 'bigint')\n        return String(value);\n    const num = typeof value === 'number' ? value : Number(value);\n    if (!isFinite(num))\n        return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n    let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n    if (!format &&\n        minFractionDigits &&\n        (!tag || tag === 'tag:yaml.org,2002:float') &&\n        /^-?\\d/.test(n) &&\n        !n.includes('e')) {\n        let i = n.indexOf('.');\n        if (i < 0) {\n            i = n.length;\n            n += '.';\n        }\n        let d = minFractionDigits - (n.length - i - 1);\n        while (d-- > 0)\n            n += '0';\n    }\n    return n;\n}\n\nexports.stringifyNumber = stringifyNumber;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: str => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n    resolve: str => parseFloat(str),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n    resolve(str) {\n        const node = new Scalar.Scalar(parseFloat(str));\n        const dot = str.indexOf('.');\n        if (dot !== -1 && str[str.length - 1] === '0')\n            node.minFractionDigits = str.length - dot - 1;\n        return node;\n    },\n    stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value) && value >= 0)\n        return prefix + value.toString(radix);\n    return stringifyNumber.stringifyNumber(node);\n}\nconst intOct = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^0o[0-7]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n    stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^0x[0-9a-fA-F]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intHex = intHex;\nexports.intOct = intOct;\n","'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\n\nconst schema = [\n    map.map,\n    seq.seq,\n    string.string,\n    _null.nullTag,\n    bool.boolTag,\n    int.intOct,\n    int.int,\n    int.intHex,\n    float.floatNaN,\n    float.floatExp,\n    float.float\n];\n\nexports.schema = schema;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar map = require('../common/map.js');\nvar seq = require('../common/seq.js');\n\nfunction intIdentify(value) {\n    return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n    {\n        identify: value => typeof value === 'string',\n        default: true,\n        tag: 'tag:yaml.org,2002:str',\n        resolve: str => str,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => value == null,\n        createNode: () => new Scalar.Scalar(null),\n        default: true,\n        tag: 'tag:yaml.org,2002:null',\n        test: /^null$/,\n        resolve: () => null,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => typeof value === 'boolean',\n        default: true,\n        tag: 'tag:yaml.org,2002:bool',\n        test: /^true$|^false$/,\n        resolve: str => str === 'true',\n        stringify: stringifyJSON\n    },\n    {\n        identify: intIdentify,\n        default: true,\n        tag: 'tag:yaml.org,2002:int',\n        test: /^-?(?:0|[1-9][0-9]*)$/,\n        resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n        stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n    },\n    {\n        identify: value => typeof value === 'number',\n        default: true,\n        tag: 'tag:yaml.org,2002:float',\n        test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n        resolve: str => parseFloat(str),\n        stringify: stringifyJSON\n    }\n];\nconst jsonError = {\n    default: true,\n    tag: '',\n    test: /^/,\n    resolve(str, onError) {\n        onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n        return str;\n    }\n};\nconst schema = [map.map, seq.seq].concat(jsonScalars, jsonError);\n\nexports.schema = schema;\n","'use strict';\n\nvar node_buffer = require('buffer');\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst binary = {\n    identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n    default: false,\n    tag: 'tag:yaml.org,2002:binary',\n    /**\n     * Returns a Buffer in node and an Uint8Array in browsers\n     *\n     * To use the resulting buffer as an image, you'll want to do something like:\n     *\n     *   const blob = new Blob([buffer], { type: 'image/jpeg' })\n     *   document.querySelector('#photo').src = URL.createObjectURL(blob)\n     */\n    resolve(src, onError) {\n        if (typeof node_buffer.Buffer === 'function') {\n            return node_buffer.Buffer.from(src, 'base64');\n        }\n        else if (typeof atob === 'function') {\n            // On IE 11, atob() can't handle newlines\n            const str = atob(src.replace(/[\\n\\r]/g, ''));\n            const buffer = new Uint8Array(str.length);\n            for (let i = 0; i < str.length; ++i)\n                buffer[i] = str.charCodeAt(i);\n            return buffer;\n        }\n        else {\n            onError('This environment does not support reading binary tags; either Buffer or atob is required');\n            return src;\n        }\n    },\n    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n        if (!value)\n            return '';\n        const buf = value; // checked earlier by binary.identify()\n        let str;\n        if (typeof node_buffer.Buffer === 'function') {\n            str =\n                buf instanceof node_buffer.Buffer\n                    ? buf.toString('base64')\n                    : node_buffer.Buffer.from(buf.buffer).toString('base64');\n        }\n        else if (typeof btoa === 'function') {\n            let s = '';\n            for (let i = 0; i < buf.length; ++i)\n                s += String.fromCharCode(buf[i]);\n            str = btoa(s);\n        }\n        else {\n            throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n        }\n        type ?? (type = Scalar.Scalar.BLOCK_LITERAL);\n        if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n            const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n            const n = Math.ceil(str.length / lineWidth);\n            const lines = new Array(n);\n            for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n                lines[i] = str.substr(o, lineWidth);\n            }\n            str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n        }\n        return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n    }\n};\n\nexports.binary = binary;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar Scalar = require('../../nodes/Scalar.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nfunction resolvePairs(seq, onError) {\n    if (identity.isSeq(seq)) {\n        for (let i = 0; i < seq.items.length; ++i) {\n            let item = seq.items[i];\n            if (identity.isPair(item))\n                continue;\n            else if (identity.isMap(item)) {\n                if (item.items.length > 1)\n                    onError('Each pair must have its own sequence indicator');\n                const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));\n                if (item.commentBefore)\n                    pair.key.commentBefore = pair.key.commentBefore\n                        ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n                        : item.commentBefore;\n                if (item.comment) {\n                    const cn = pair.value ?? pair.key;\n                    cn.comment = cn.comment\n                        ? `${item.comment}\\n${cn.comment}`\n                        : item.comment;\n                }\n                item = pair;\n            }\n            seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);\n        }\n    }\n    else\n        onError('Expected a sequence for this tag');\n    return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n    const { replacer } = ctx;\n    const pairs = new YAMLSeq.YAMLSeq(schema);\n    pairs.tag = 'tag:yaml.org,2002:pairs';\n    let i = 0;\n    if (iterable && Symbol.iterator in Object(iterable))\n        for (let it of iterable) {\n            if (typeof replacer === 'function')\n                it = replacer.call(iterable, String(i++), it);\n            let key, value;\n            if (Array.isArray(it)) {\n                if (it.length === 2) {\n                    key = it[0];\n                    value = it[1];\n                }\n                else\n                    throw new TypeError(`Expected [key, value] tuple: ${it}`);\n            }\n            else if (it && it instanceof Object) {\n                const keys = Object.keys(it);\n                if (keys.length === 1) {\n                    key = keys[0];\n                    value = it[key];\n                }\n                else {\n                    throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n                }\n            }\n            else {\n                key = it;\n            }\n            pairs.items.push(Pair.createPair(key, value, ctx));\n        }\n    return pairs;\n}\nconst pairs = {\n    collection: 'seq',\n    default: false,\n    tag: 'tag:yaml.org,2002:pairs',\n    resolve: resolvePairs,\n    createNode: createPairs\n};\n\nexports.createPairs = createPairs;\nexports.pairs = pairs;\nexports.resolvePairs = resolvePairs;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar toJS = require('../../nodes/toJS.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\nvar pairs = require('./pairs.js');\n\nclass YAMLOMap extends YAMLSeq.YAMLSeq {\n    constructor() {\n        super();\n        this.add = YAMLMap.YAMLMap.prototype.add.bind(this);\n        this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);\n        this.get = YAMLMap.YAMLMap.prototype.get.bind(this);\n        this.has = YAMLMap.YAMLMap.prototype.has.bind(this);\n        this.set = YAMLMap.YAMLMap.prototype.set.bind(this);\n        this.tag = YAMLOMap.tag;\n    }\n    /**\n     * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n     * but TypeScript won't allow widening the signature of a child method.\n     */\n    toJSON(_, ctx) {\n        if (!ctx)\n            return super.toJSON(_);\n        const map = new Map();\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const pair of this.items) {\n            let key, value;\n            if (identity.isPair(pair)) {\n                key = toJS.toJS(pair.key, '', ctx);\n                value = toJS.toJS(pair.value, key, ctx);\n            }\n            else {\n                key = toJS.toJS(pair, '', ctx);\n            }\n            if (map.has(key))\n                throw new Error('Ordered maps must not include duplicate keys');\n            map.set(key, value);\n        }\n        return map;\n    }\n    static from(schema, iterable, ctx) {\n        const pairs$1 = pairs.createPairs(schema, iterable, ctx);\n        const omap = new this();\n        omap.items = pairs$1.items;\n        return omap;\n    }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n    collection: 'seq',\n    identify: value => value instanceof Map,\n    nodeClass: YAMLOMap,\n    default: false,\n    tag: 'tag:yaml.org,2002:omap',\n    resolve(seq, onError) {\n        const pairs$1 = pairs.resolvePairs(seq, onError);\n        const seenKeys = [];\n        for (const { key } of pairs$1.items) {\n            if (identity.isScalar(key)) {\n                if (seenKeys.includes(key.value)) {\n                    onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n                }\n                else {\n                    seenKeys.push(key.value);\n                }\n            }\n        }\n        return Object.assign(new YAMLOMap(), pairs$1);\n    },\n    createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexports.YAMLOMap = YAMLOMap;\nexports.omap = omap;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nfunction boolStringify({ value, source }, ctx) {\n    const boolObj = value ? trueTag : falseTag;\n    if (source && boolObj.test.test(source))\n        return source;\n    return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n    identify: value => value === true,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n    resolve: () => new Scalar.Scalar(true),\n    stringify: boolStringify\n};\nconst falseTag = {\n    identify: value => value === false,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n    resolve: () => new Scalar.Scalar(false),\n    stringify: boolStringify\n};\n\nexports.falseTag = falseTag;\nexports.trueTag = trueTag;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n    resolve: (str) => parseFloat(str.replace(/_/g, '')),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n    resolve(str) {\n        const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));\n        const dot = str.indexOf('.');\n        if (dot !== -1) {\n            const f = str.substring(dot + 1).replace(/_/g, '');\n            if (f[f.length - 1] === '0')\n                node.minFractionDigits = f.length;\n        }\n        return node;\n    },\n    stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n    const sign = str[0];\n    if (sign === '-' || sign === '+')\n        offset += 1;\n    str = str.substring(offset).replace(/_/g, '');\n    if (intAsBigInt) {\n        switch (radix) {\n            case 2:\n                str = `0b${str}`;\n                break;\n            case 8:\n                str = `0o${str}`;\n                break;\n            case 16:\n                str = `0x${str}`;\n                break;\n        }\n        const n = BigInt(str);\n        return sign === '-' ? BigInt(-1) * n : n;\n    }\n    const n = parseInt(str, radix);\n    return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value)) {\n        const str = value.toString(radix);\n        return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n    }\n    return stringifyNumber.stringifyNumber(node);\n}\nconst intBin = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'BIN',\n    test: /^[-+]?0b[0-1_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n    stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^[-+]?0[0-7_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n    stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9][0-9_]*$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^[-+]?0x[0-9a-fA-F_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intBin = intBin;\nexports.intHex = intHex;\nexports.intOct = intOct;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nclass YAMLSet extends YAMLMap.YAMLMap {\n    constructor(schema) {\n        super(schema);\n        this.tag = YAMLSet.tag;\n    }\n    add(key) {\n        let pair;\n        if (identity.isPair(key))\n            pair = key;\n        else if (key &&\n            typeof key === 'object' &&\n            'key' in key &&\n            'value' in key &&\n            key.value === null)\n            pair = new Pair.Pair(key.key, null);\n        else\n            pair = new Pair.Pair(key, null);\n        const prev = YAMLMap.findPair(this.items, pair.key);\n        if (!prev)\n            this.items.push(pair);\n    }\n    /**\n     * If `keepPair` is `true`, returns the Pair matching `key`.\n     * Otherwise, returns the value of that Pair's key.\n     */\n    get(key, keepPair) {\n        const pair = YAMLMap.findPair(this.items, key);\n        return !keepPair && identity.isPair(pair)\n            ? identity.isScalar(pair.key)\n                ? pair.key.value\n                : pair.key\n            : pair;\n    }\n    set(key, value) {\n        if (typeof value !== 'boolean')\n            throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n        const prev = YAMLMap.findPair(this.items, key);\n        if (prev && !value) {\n            this.items.splice(this.items.indexOf(prev), 1);\n        }\n        else if (!prev && value) {\n            this.items.push(new Pair.Pair(key));\n        }\n    }\n    toJSON(_, ctx) {\n        return super.toJSON(_, ctx, Set);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        if (this.hasAllNullValues(true))\n            return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n        else\n            throw new Error('Set items must all have null values');\n    }\n    static from(schema, iterable, ctx) {\n        const { replacer } = ctx;\n        const set = new this(schema);\n        if (iterable && Symbol.iterator in Object(iterable))\n            for (let value of iterable) {\n                if (typeof replacer === 'function')\n                    value = replacer.call(iterable, value, value);\n                set.items.push(Pair.createPair(value, null, ctx));\n            }\n        return set;\n    }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n    collection: 'map',\n    identify: value => value instanceof Set,\n    nodeClass: YAMLSet,\n    default: false,\n    tag: 'tag:yaml.org,2002:set',\n    createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n    resolve(map, onError) {\n        if (identity.isMap(map)) {\n            if (map.hasAllNullValues(true))\n                return Object.assign(new YAMLSet(), map);\n            else\n                onError('Set items must all have null values');\n        }\n        else\n            onError('Expected a mapping for this tag');\n        return map;\n    }\n};\n\nexports.YAMLSet = YAMLSet;\nexports.set = set;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n    const sign = str[0];\n    const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n    const num = (n) => asBigInt ? BigInt(n) : Number(n);\n    const res = parts\n        .replace(/_/g, '')\n        .split(':')\n        .reduce((res, p) => res * num(60) + num(p), num(0));\n    return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n    let { value } = node;\n    let num = (n) => n;\n    if (typeof value === 'bigint')\n        num = n => BigInt(n);\n    else if (isNaN(value) || !isFinite(value))\n        return stringifyNumber.stringifyNumber(node);\n    let sign = '';\n    if (value < 0) {\n        sign = '-';\n        value *= num(-1);\n    }\n    const _60 = num(60);\n    const parts = [value % _60]; // seconds, including ms\n    if (value < 60) {\n        parts.unshift(0); // at least one : is required\n    }\n    else {\n        value = (value - parts[0]) / _60;\n        parts.unshift(value % _60); // minutes\n        if (value >= 60) {\n            value = (value - parts[0]) / _60;\n            parts.unshift(value); // hours\n        }\n    }\n    return (sign +\n        parts\n            .map(n => String(n).padStart(2, '0'))\n            .join(':')\n            .replace(/000000\\d*$/, '') // % 60 may introduce error\n    );\n}\nconst intTime = {\n    identify: value => typeof value === 'bigint' || Number.isInteger(value),\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n    stringify: stringifySexagesimal\n};\nconst floatTime = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n    resolve: str => parseSexagesimal(str, false),\n    stringify: stringifySexagesimal\n};\nconst timestamp = {\n    identify: value => value instanceof Date,\n    default: true,\n    tag: 'tag:yaml.org,2002:timestamp',\n    // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n    // may be omitted altogether, resulting in a date format. In such a case, the time part is\n    // assumed to be 00:00:00Z (start of day, UTC).\n    test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n        '(?:' + // time is optional\n        '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n        '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n        '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n        ')?$'),\n    resolve(str) {\n        const match = str.match(timestamp.test);\n        if (!match)\n            throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n        const [, year, month, day, hour, minute, second] = match.map(Number);\n        const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n        let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n        const tz = match[8];\n        if (tz && tz !== 'Z') {\n            let d = parseSexagesimal(tz, false);\n            if (Math.abs(d) < 30)\n                d *= 60;\n            date -= 60000 * d;\n        }\n        return new Date(date);\n    },\n    stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexports.floatTime = floatTime;\nexports.intTime = intTime;\nexports.timestamp = timestamp;\n","'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar binary = require('./binary.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\nvar merge = require('./merge.js');\nvar omap = require('./omap.js');\nvar pairs = require('./pairs.js');\nvar set = require('./set.js');\nvar timestamp = require('./timestamp.js');\n\nconst schema = [\n    map.map,\n    seq.seq,\n    string.string,\n    _null.nullTag,\n    bool.trueTag,\n    bool.falseTag,\n    int.intBin,\n    int.intOct,\n    int.int,\n    int.intHex,\n    float.floatNaN,\n    float.floatExp,\n    float.float,\n    binary.binary,\n    merge.merge,\n    omap.omap,\n    pairs.pairs,\n    set.set,\n    timestamp.intTime,\n    timestamp.floatTime,\n    timestamp.timestamp\n];\n\nexports.schema = schema;\n","'use strict';\n\nvar map = require('./common/map.js');\nvar _null = require('./common/null.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar bool = require('./core/bool.js');\nvar float = require('./core/float.js');\nvar int = require('./core/int.js');\nvar schema = require('./core/schema.js');\nvar schema$1 = require('./json/schema.js');\nvar binary = require('./yaml-1.1/binary.js');\nvar merge = require('./yaml-1.1/merge.js');\nvar omap = require('./yaml-1.1/omap.js');\nvar pairs = require('./yaml-1.1/pairs.js');\nvar schema$2 = require('./yaml-1.1/schema.js');\nvar set = require('./yaml-1.1/set.js');\nvar timestamp = require('./yaml-1.1/timestamp.js');\n\nconst schemas = new Map([\n    ['core', schema.schema],\n    ['failsafe', [map.map, seq.seq, string.string]],\n    ['json', schema$1.schema],\n    ['yaml11', schema$2.schema],\n    ['yaml-1.1', schema$2.schema]\n]);\nconst tagsByName = {\n    binary: binary.binary,\n    bool: bool.boolTag,\n    float: float.float,\n    floatExp: float.floatExp,\n    floatNaN: float.floatNaN,\n    floatTime: timestamp.floatTime,\n    int: int.int,\n    intHex: int.intHex,\n    intOct: int.intOct,\n    intTime: timestamp.intTime,\n    map: map.map,\n    merge: merge.merge,\n    null: _null.nullTag,\n    omap: omap.omap,\n    pairs: pairs.pairs,\n    seq: seq.seq,\n    set: set.set,\n    timestamp: timestamp.timestamp\n};\nconst coreKnownTags = {\n    'tag:yaml.org,2002:binary': binary.binary,\n    'tag:yaml.org,2002:merge': merge.merge,\n    'tag:yaml.org,2002:omap': omap.omap,\n    'tag:yaml.org,2002:pairs': pairs.pairs,\n    'tag:yaml.org,2002:set': set.set,\n    'tag:yaml.org,2002:timestamp': timestamp.timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n    const schemaTags = schemas.get(schemaName);\n    if (schemaTags && !customTags) {\n        return addMergeTag && !schemaTags.includes(merge.merge)\n            ? schemaTags.concat(merge.merge)\n            : schemaTags.slice();\n    }\n    let tags = schemaTags;\n    if (!tags) {\n        if (Array.isArray(customTags))\n            tags = [];\n        else {\n            const keys = Array.from(schemas.keys())\n                .filter(key => key !== 'yaml11')\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n        }\n    }\n    if (Array.isArray(customTags)) {\n        for (const tag of customTags)\n            tags = tags.concat(tag);\n    }\n    else if (typeof customTags === 'function') {\n        tags = customTags(tags.slice());\n    }\n    if (addMergeTag)\n        tags = tags.concat(merge.merge);\n    return tags.reduce((tags, tag) => {\n        const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n        if (!tagObj) {\n            const tagName = JSON.stringify(tag);\n            const keys = Object.keys(tagsByName)\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n        }\n        if (!tags.includes(tagObj))\n            tags.push(tagObj);\n        return tags;\n    }, []);\n}\n\nexports.coreKnownTags = coreKnownTags;\nexports.getTags = getTags;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar map = require('./common/map.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar tags = require('./tags.js');\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n    constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n        this.compat = Array.isArray(compat)\n            ? tags.getTags(compat, 'compat')\n            : compat\n                ? tags.getTags(null, compat)\n                : null;\n        this.name = (typeof schema === 'string' && schema) || 'core';\n        this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};\n        this.tags = tags.getTags(customTags, this.name, merge);\n        this.toStringOptions = toStringDefaults ?? null;\n        Object.defineProperty(this, identity.MAP, { value: map.map });\n        Object.defineProperty(this, identity.SCALAR, { value: string.string });\n        Object.defineProperty(this, identity.SEQ, { value: seq.seq });\n        // Used by createMap()\n        this.sortMapEntries =\n            typeof sortMapEntries === 'function'\n                ? sortMapEntries\n                : sortMapEntries === true\n                    ? sortMapEntriesByKey\n                    : null;\n    }\n    clone() {\n        const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n        copy.tags = this.tags.slice();\n        return copy;\n    }\n}\n\nexports.Schema = Schema;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyDocument(doc, options) {\n    const lines = [];\n    let hasDirectives = options.directives === true;\n    if (options.directives !== false && doc.directives) {\n        const dir = doc.directives.toString(doc);\n        if (dir) {\n            lines.push(dir);\n            hasDirectives = true;\n        }\n        else if (doc.directives.docStart)\n            hasDirectives = true;\n    }\n    if (hasDirectives)\n        lines.push('---');\n    const ctx = stringify.createStringifyContext(doc, options);\n    const { commentString } = ctx.options;\n    if (doc.commentBefore) {\n        if (lines.length !== 1)\n            lines.unshift('');\n        const cs = commentString(doc.commentBefore);\n        lines.unshift(stringifyComment.indentComment(cs, ''));\n    }\n    let chompKeep = false;\n    let contentComment = null;\n    if (doc.contents) {\n        if (identity.isNode(doc.contents)) {\n            if (doc.contents.spaceBefore && hasDirectives)\n                lines.push('');\n            if (doc.contents.commentBefore) {\n                const cs = commentString(doc.contents.commentBefore);\n                lines.push(stringifyComment.indentComment(cs, ''));\n            }\n            // top-level block scalars need to be indented if followed by a comment\n            ctx.forceBlockIndent = !!doc.comment;\n            contentComment = doc.contents.comment;\n        }\n        const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n        let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n        if (contentComment)\n            body += stringifyComment.lineComment(body, '', commentString(contentComment));\n        if ((body[0] === '|' || body[0] === '>') &&\n            lines[lines.length - 1] === '---') {\n            // Top-level block scalars with a preceding doc marker ought to use the\n            // same line for their header.\n            lines[lines.length - 1] = `--- ${body}`;\n        }\n        else\n            lines.push(body);\n    }\n    else {\n        lines.push(stringify.stringify(doc.contents, ctx));\n    }\n    if (doc.directives?.docEnd) {\n        if (doc.comment) {\n            const cs = commentString(doc.comment);\n            if (cs.includes('\\n')) {\n                lines.push('...');\n                lines.push(stringifyComment.indentComment(cs, ''));\n            }\n            else {\n                lines.push(`... ${cs}`);\n            }\n        }\n        else {\n            lines.push('...');\n        }\n    }\n    else {\n        let dc = doc.comment;\n        if (dc && chompKeep)\n            dc = dc.replace(/^\\n+/, '');\n        if (dc) {\n            if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n                lines.push('');\n            lines.push(stringifyComment.indentComment(commentString(dc), ''));\n        }\n    }\n    return lines.join('\\n') + '\\n';\n}\n\nexports.stringifyDocument = stringifyDocument;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar Collection = require('../nodes/Collection.js');\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar toJS = require('../nodes/toJS.js');\nvar Schema = require('../schema/Schema.js');\nvar stringifyDocument = require('../stringify/stringifyDocument.js');\nvar anchors = require('./anchors.js');\nvar applyReviver = require('./applyReviver.js');\nvar createNode = require('./createNode.js');\nvar directives = require('./directives.js');\n\nclass Document {\n    constructor(value, replacer, options) {\n        /** A comment before this Document */\n        this.commentBefore = null;\n        /** A comment immediately after this Document */\n        this.comment = null;\n        /** Errors encountered during parsing. */\n        this.errors = [];\n        /** Warnings encountered during parsing. */\n        this.warnings = [];\n        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });\n        let _replacer = null;\n        if (typeof replacer === 'function' || Array.isArray(replacer)) {\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const opt = Object.assign({\n            intAsBigInt: false,\n            keepSourceTokens: false,\n            logLevel: 'warn',\n            prettyErrors: true,\n            strict: true,\n            stringKeys: false,\n            uniqueKeys: true,\n            version: '1.2'\n        }, options);\n        this.options = opt;\n        let { version } = opt;\n        if (options?._directives) {\n            this.directives = options._directives.atDocument();\n            if (this.directives.yaml.explicit)\n                version = this.directives.yaml.version;\n        }\n        else\n            this.directives = new directives.Directives({ version });\n        this.setSchema(version, options);\n        // @ts-expect-error We can't really know that this matches Contents.\n        this.contents =\n            value === undefined ? null : this.createNode(value, _replacer, options);\n    }\n    /**\n     * Create a deep copy of this Document and its contents.\n     *\n     * Custom Node values that inherit from `Object` still refer to their original instances.\n     */\n    clone() {\n        const copy = Object.create(Document.prototype, {\n            [identity.NODE_TYPE]: { value: identity.DOC }\n        });\n        copy.commentBefore = this.commentBefore;\n        copy.comment = this.comment;\n        copy.errors = this.errors.slice();\n        copy.warnings = this.warnings.slice();\n        copy.options = Object.assign({}, this.options);\n        if (this.directives)\n            copy.directives = this.directives.clone();\n        copy.schema = this.schema.clone();\n        // @ts-expect-error We can't really know that this matches Contents.\n        copy.contents = identity.isNode(this.contents)\n            ? this.contents.clone(copy.schema)\n            : this.contents;\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** Adds a value to the document. */\n    add(value) {\n        if (assertCollection(this.contents))\n            this.contents.add(value);\n    }\n    /** Adds a value to the document. */\n    addIn(path, value) {\n        if (assertCollection(this.contents))\n            this.contents.addIn(path, value);\n    }\n    /**\n     * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n     *\n     * If `node` already has an anchor, `name` is ignored.\n     * Otherwise, the `node.anchor` value will be set to `name`,\n     * or if an anchor with that name is already present in the document,\n     * `name` will be used as a prefix for a new unique anchor.\n     * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n     */\n    createAlias(node, name) {\n        if (!node.anchor) {\n            const prev = anchors.anchorNames(this);\n            node.anchor =\n                // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n                !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;\n        }\n        return new Alias.Alias(node.anchor);\n    }\n    createNode(value, replacer, options) {\n        let _replacer = undefined;\n        if (typeof replacer === 'function') {\n            value = replacer.call({ '': value }, '', value);\n            _replacer = replacer;\n        }\n        else if (Array.isArray(replacer)) {\n            const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n            const asStr = replacer.filter(keyToStr).map(String);\n            if (asStr.length > 0)\n                replacer = replacer.concat(asStr);\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n        const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, \n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        anchorPrefix || 'a');\n        const ctx = {\n            aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n            keepUndefined: keepUndefined ?? false,\n            onAnchor,\n            onTagObj,\n            replacer: _replacer,\n            schema: this.schema,\n            sourceObjects\n        };\n        const node = createNode.createNode(value, tag, ctx);\n        if (flow && identity.isCollection(node))\n            node.flow = true;\n        setAnchors();\n        return node;\n    }\n    /**\n     * Convert a key and a value into a `Pair` using the current schema,\n     * recursively wrapping all values as `Scalar` or `Collection` nodes.\n     */\n    createPair(key, value, options = {}) {\n        const k = this.createNode(key, null, options);\n        const v = this.createNode(value, null, options);\n        return new Pair.Pair(k, v);\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        return assertCollection(this.contents) ? this.contents.delete(key) : false;\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        if (Collection.isEmptyPath(path)) {\n            if (this.contents == null)\n                return false;\n            // @ts-expect-error Presumed impossible if Strict extends false\n            this.contents = null;\n            return true;\n        }\n        return assertCollection(this.contents)\n            ? this.contents.deleteIn(path)\n            : false;\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    get(key, keepScalar) {\n        return identity.isCollection(this.contents)\n            ? this.contents.get(key, keepScalar)\n            : undefined;\n    }\n    /**\n     * Returns item at `path`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        if (Collection.isEmptyPath(path))\n            return !keepScalar && identity.isScalar(this.contents)\n                ? this.contents.value\n                : this.contents;\n        return identity.isCollection(this.contents)\n            ? this.contents.getIn(path, keepScalar)\n            : undefined;\n    }\n    /**\n     * Checks if the document includes a value with the key `key`.\n     */\n    has(key) {\n        return identity.isCollection(this.contents) ? this.contents.has(key) : false;\n    }\n    /**\n     * Checks if the document includes a value at `path`.\n     */\n    hasIn(path) {\n        if (Collection.isEmptyPath(path))\n            return this.contents !== undefined;\n        return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    set(key, value) {\n        if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = Collection.collectionFromPath(this.schema, [key], value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.set(key, value);\n        }\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        if (Collection.isEmptyPath(path)) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = value;\n        }\n        else if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.setIn(path, value);\n        }\n    }\n    /**\n     * Change the YAML version and schema used by the document.\n     * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n     * It also requires the `schema` option to be given as a `Schema` instance value.\n     *\n     * Overrides all previously set schema options.\n     */\n    setSchema(version, options = {}) {\n        if (typeof version === 'number')\n            version = String(version);\n        let opt;\n        switch (version) {\n            case '1.1':\n                if (this.directives)\n                    this.directives.yaml.version = '1.1';\n                else\n                    this.directives = new directives.Directives({ version: '1.1' });\n                opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n                break;\n            case '1.2':\n            case 'next':\n                if (this.directives)\n                    this.directives.yaml.version = version;\n                else\n                    this.directives = new directives.Directives({ version });\n                opt = { resolveKnownTags: true, schema: 'core' };\n                break;\n            case null:\n                if (this.directives)\n                    delete this.directives;\n                opt = null;\n                break;\n            default: {\n                const sv = JSON.stringify(version);\n                throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n            }\n        }\n        // Not using `instanceof Schema` to allow for duck typing\n        if (options.schema instanceof Object)\n            this.schema = options.schema;\n        else if (opt)\n            this.schema = new Schema.Schema(Object.assign(opt, options));\n        else\n            throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n    }\n    // json & jsonArg are only used from toJSON()\n    toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        const ctx = {\n            anchors: new Map(),\n            doc: this,\n            keep: !json,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n    /**\n     * A JSON representation of the document `contents`.\n     *\n     * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n     *   property name.\n     */\n    toJSON(jsonArg, onAnchor) {\n        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n    }\n    /** A YAML representation of the document. */\n    toString(options = {}) {\n        if (this.errors.length > 0)\n            throw new Error('Document with errors cannot be stringified');\n        if ('indent' in options &&\n            (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n            const s = JSON.stringify(options.indent);\n            throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n        }\n        return stringifyDocument.stringifyDocument(this, options);\n    }\n}\nfunction assertCollection(contents) {\n    if (identity.isCollection(contents))\n        return true;\n    throw new Error('Expected a YAML collection as document contents');\n}\n\nexports.Document = Document;\n","'use strict';\n\nclass YAMLError extends Error {\n    constructor(name, pos, code, message) {\n        super();\n        this.name = name;\n        this.code = code;\n        this.message = message;\n        this.pos = pos;\n    }\n}\nclass YAMLParseError extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLParseError', pos, code, message);\n    }\n}\nclass YAMLWarning extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLWarning', pos, code, message);\n    }\n}\nconst prettifyError = (src, lc) => (error) => {\n    if (error.pos[0] === -1)\n        return;\n    error.linePos = error.pos.map(pos => lc.linePos(pos));\n    const { line, col } = error.linePos[0];\n    error.message += ` at line ${line}, column ${col}`;\n    let ci = col - 1;\n    let lineStr = src\n        .substring(lc.lineStarts[line - 1], lc.lineStarts[line])\n        .replace(/[\\n\\r]+$/, '');\n    // Trim to max 80 chars, keeping col position near the middle\n    if (ci >= 60 && lineStr.length > 80) {\n        const trimStart = Math.min(ci - 39, lineStr.length - 79);\n        lineStr = '…' + lineStr.substring(trimStart);\n        ci -= trimStart - 1;\n    }\n    if (lineStr.length > 80)\n        lineStr = lineStr.substring(0, 79) + '…';\n    // Include previous line in context if pointing at line start\n    if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {\n        // Regexp won't match if start is trimmed\n        let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);\n        if (prev.length > 80)\n            prev = prev.substring(0, 79) + '…\\n';\n        lineStr = prev + lineStr;\n    }\n    if (/[^ ]/.test(lineStr)) {\n        let count = 1;\n        const end = error.linePos[1];\n        if (end?.line === line && end.col > col) {\n            count = Math.max(1, Math.min(end.col - col, 80 - ci));\n        }\n        const pointer = ' '.repeat(ci) + '^'.repeat(count);\n        error.message += `:\\n\\n${lineStr}\\n${pointer}\\n`;\n    }\n};\n\nexports.YAMLError = YAMLError;\nexports.YAMLParseError = YAMLParseError;\nexports.YAMLWarning = YAMLWarning;\nexports.prettifyError = prettifyError;\n","'use strict';\n\nfunction resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {\n    let spaceBefore = false;\n    let atNewline = startOnNewline;\n    let hasSpace = startOnNewline;\n    let comment = '';\n    let commentSep = '';\n    let hasNewline = false;\n    let reqSpace = false;\n    let tab = null;\n    let anchor = null;\n    let tag = null;\n    let newlineAfterProp = null;\n    let comma = null;\n    let found = null;\n    let start = null;\n    for (const token of tokens) {\n        if (reqSpace) {\n            if (token.type !== 'space' &&\n                token.type !== 'newline' &&\n                token.type !== 'comma')\n                onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n            reqSpace = false;\n        }\n        if (tab) {\n            if (atNewline && token.type !== 'comment' && token.type !== 'newline') {\n                onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n            }\n            tab = null;\n        }\n        switch (token.type) {\n            case 'space':\n                // At the doc level, tabs at line start may be parsed\n                // as leading white space rather than indentation.\n                // In a flow collection, only the parser handles indent.\n                if (!flow &&\n                    (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&\n                    token.source.includes('\\t')) {\n                    tab = token;\n                }\n                hasSpace = true;\n                break;\n            case 'comment': {\n                if (!hasSpace)\n                    onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                const cb = token.source.substring(1) || ' ';\n                if (!comment)\n                    comment = cb;\n                else\n                    comment += commentSep + cb;\n                commentSep = '';\n                atNewline = false;\n                break;\n            }\n            case 'newline':\n                if (atNewline) {\n                    if (comment)\n                        comment += token.source;\n                    else if (!found || indicator !== 'seq-item-ind')\n                        spaceBefore = true;\n                }\n                else\n                    commentSep += token.source;\n                atNewline = true;\n                hasNewline = true;\n                if (anchor || tag)\n                    newlineAfterProp = token;\n                hasSpace = true;\n                break;\n            case 'anchor':\n                if (anchor)\n                    onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');\n                if (token.source.endsWith(':'))\n                    onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);\n                anchor = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            case 'tag': {\n                if (tag)\n                    onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');\n                tag = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            }\n            case indicator:\n                // Could here handle preceding comments differently\n                if (anchor || tag)\n                    onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);\n                if (found)\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);\n                found = token;\n                atNewline =\n                    indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';\n                hasSpace = false;\n                break;\n            case 'comma':\n                if (flow) {\n                    if (comma)\n                        onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);\n                    comma = token;\n                    atNewline = false;\n                    hasSpace = false;\n                    break;\n                }\n            // else fallthrough\n            default:\n                onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);\n                atNewline = false;\n                hasSpace = false;\n        }\n    }\n    const last = tokens[tokens.length - 1];\n    const end = last ? last.offset + last.source.length : offset;\n    if (reqSpace &&\n        next &&\n        next.type !== 'space' &&\n        next.type !== 'newline' &&\n        next.type !== 'comma' &&\n        (next.type !== 'scalar' || next.source !== '')) {\n        onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n    }\n    if (tab &&\n        ((atNewline && tab.indent <= parentIndent) ||\n            next?.type === 'block-map' ||\n            next?.type === 'block-seq'))\n        onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n    return {\n        comma,\n        found,\n        spaceBefore,\n        comment,\n        hasNewline,\n        anchor,\n        tag,\n        newlineAfterProp,\n        end,\n        start: start ?? end\n    };\n}\n\nexports.resolveProps = resolveProps;\n","'use strict';\n\nfunction containsNewline(key) {\n    if (!key)\n        return null;\n    switch (key.type) {\n        case 'alias':\n        case 'scalar':\n        case 'double-quoted-scalar':\n        case 'single-quoted-scalar':\n            if (key.source.includes('\\n'))\n                return true;\n            if (key.end)\n                for (const st of key.end)\n                    if (st.type === 'newline')\n                        return true;\n            return false;\n        case 'flow-collection':\n            for (const it of key.items) {\n                for (const st of it.start)\n                    if (st.type === 'newline')\n                        return true;\n                if (it.sep)\n                    for (const st of it.sep)\n                        if (st.type === 'newline')\n                            return true;\n                if (containsNewline(it.key) || containsNewline(it.value))\n                    return true;\n            }\n            return false;\n        default:\n            return true;\n    }\n}\n\nexports.containsNewline = containsNewline;\n","'use strict';\n\nvar utilContainsNewline = require('./util-contains-newline.js');\n\nfunction flowIndentCheck(indent, fc, onError) {\n    if (fc?.type === 'flow-collection') {\n        const end = fc.end[0];\n        if (end.indent === indent &&\n            (end.source === ']' || end.source === '}') &&\n            utilContainsNewline.containsNewline(fc)) {\n            const msg = 'Flow end indicator should be more indented than parent';\n            onError(end, 'BAD_INDENT', msg, true);\n        }\n    }\n}\n\nexports.flowIndentCheck = flowIndentCheck;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\n\nfunction mapIncludes(ctx, items, search) {\n    const { uniqueKeys } = ctx.options;\n    if (uniqueKeys === false)\n        return false;\n    const isEqual = typeof uniqueKeys === 'function'\n        ? uniqueKeys\n        : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value);\n    return items.some(pair => isEqual(pair.key, search));\n}\n\nexports.mapIncludes = mapIncludes;\n","'use strict';\n\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst startColMsg = 'All mapping items must start at the same column';\nfunction resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;\n    const map = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    let offset = bm.offset;\n    let commentEnd = null;\n    for (const collItem of bm.items) {\n        const { start, key, sep, value } = collItem;\n        // key properties\n        const keyProps = resolveProps.resolveProps(start, {\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: true\n        });\n        const implicitKey = !keyProps.found;\n        if (implicitKey) {\n            if (key) {\n                if (key.type === 'block-seq')\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');\n                else if ('indent' in key && key.indent !== bm.indent)\n                    onError(offset, 'BAD_INDENT', startColMsg);\n            }\n            if (!keyProps.anchor && !keyProps.tag && !sep) {\n                commentEnd = keyProps.end;\n                if (keyProps.comment) {\n                    if (map.comment)\n                        map.comment += '\\n' + keyProps.comment;\n                    else\n                        map.comment = keyProps.comment;\n                }\n                continue;\n            }\n            if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {\n                onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');\n            }\n        }\n        else if (keyProps.found?.indent !== bm.indent) {\n            onError(offset, 'BAD_INDENT', startColMsg);\n        }\n        // key value\n        ctx.atKey = true;\n        const keyStart = keyProps.end;\n        const keyNode = key\n            ? composeNode(ctx, key, keyProps, onError)\n            : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);\n        if (ctx.schema.compat)\n            utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);\n        ctx.atKey = false;\n        if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n            onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n        // value properties\n        const valueProps = resolveProps.resolveProps(sep ?? [], {\n            indicator: 'map-value-ind',\n            next: value,\n            offset: keyNode.range[2],\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: !key || key.type === 'block-scalar'\n        });\n        offset = valueProps.end;\n        if (valueProps.found) {\n            if (implicitKey) {\n                if (value?.type === 'block-map' && !valueProps.hasNewline)\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');\n                if (ctx.options.strict &&\n                    keyProps.start < valueProps.found.offset - 1024)\n                    onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);\n            if (ctx.schema.compat)\n                utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);\n            offset = valueNode.range[2];\n            const pair = new Pair.Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n        else {\n            // key with no value\n            if (implicitKey)\n                onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');\n            if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair.Pair(keyNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n    }\n    if (commentEnd && commentEnd < offset)\n        onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');\n    map.range = [bm.offset, offset, commentEnd ?? offset];\n    return map;\n}\n\nexports.resolveBlockMap = resolveBlockMap;\n","'use strict';\n\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\n\nfunction resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;\n    const seq = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = bs.offset;\n    let commentEnd = null;\n    for (const { start, value } of bs.items) {\n        const props = resolveProps.resolveProps(start, {\n            indicator: 'seq-item-ind',\n            next: value,\n            offset,\n            onError,\n            parentIndent: bs.indent,\n            startOnNewline: true\n        });\n        if (!props.found) {\n            if (props.anchor || props.tag || value) {\n                if (value?.type === 'block-seq')\n                    onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');\n                else\n                    onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');\n            }\n            else {\n                commentEnd = props.end;\n                if (props.comment)\n                    seq.comment = props.comment;\n                continue;\n            }\n        }\n        const node = value\n            ? composeNode(ctx, value, props, onError)\n            : composeEmptyNode(ctx, props.end, start, null, props, onError);\n        if (ctx.schema.compat)\n            utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);\n        offset = node.range[2];\n        seq.items.push(node);\n    }\n    seq.range = [bs.offset, offset, commentEnd ?? offset];\n    return seq;\n}\n\nexports.resolveBlockSeq = resolveBlockSeq;\n","'use strict';\n\nfunction resolveEnd(end, offset, reqSpace, onError) {\n    let comment = '';\n    if (end) {\n        let hasSpace = false;\n        let sep = '';\n        for (const token of end) {\n            const { source, type } = token;\n            switch (type) {\n                case 'space':\n                    hasSpace = true;\n                    break;\n                case 'comment': {\n                    if (reqSpace && !hasSpace)\n                        onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                    const cb = source.substring(1) || ' ';\n                    if (!comment)\n                        comment = cb;\n                    else\n                        comment += sep + cb;\n                    sep = '';\n                    break;\n                }\n                case 'newline':\n                    if (comment)\n                        sep += source;\n                    hasSpace = true;\n                    break;\n                default:\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);\n            }\n            offset += source.length;\n        }\n    }\n    return { comment, offset };\n}\n\nexports.resolveEnd = resolveEnd;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst blockMsg = 'Block collections are not allowed within flow collections';\nconst isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');\nfunction resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {\n    const isMap = fc.start.source === '{';\n    const fcName = isMap ? 'flow map' : 'flow sequence';\n    const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));\n    const coll = new NodeClass(ctx.schema);\n    coll.flow = true;\n    const atRoot = ctx.atRoot;\n    if (atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = fc.offset + fc.start.source.length;\n    for (let i = 0; i < fc.items.length; ++i) {\n        const collItem = fc.items[i];\n        const { start, key, sep, value } = collItem;\n        const props = resolveProps.resolveProps(start, {\n            flow: fcName,\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: fc.indent,\n            startOnNewline: false\n        });\n        if (!props.found) {\n            if (!props.anchor && !props.tag && !sep && !value) {\n                if (i === 0 && props.comma)\n                    onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n                else if (i < fc.items.length - 1)\n                    onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);\n                if (props.comment) {\n                    if (coll.comment)\n                        coll.comment += '\\n' + props.comment;\n                    else\n                        coll.comment = props.comment;\n                }\n                offset = props.end;\n                continue;\n            }\n            if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))\n                onError(key, // checked by containsNewline()\n                'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n        }\n        if (i === 0) {\n            if (props.comma)\n                onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n        }\n        else {\n            if (!props.comma)\n                onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);\n            if (props.comment) {\n                let prevItemComment = '';\n                loop: for (const st of start) {\n                    switch (st.type) {\n                        case 'comma':\n                        case 'space':\n                            break;\n                        case 'comment':\n                            prevItemComment = st.source.substring(1);\n                            break loop;\n                        default:\n                            break loop;\n                    }\n                }\n                if (prevItemComment) {\n                    let prev = coll.items[coll.items.length - 1];\n                    if (identity.isPair(prev))\n                        prev = prev.value ?? prev.key;\n                    if (prev.comment)\n                        prev.comment += '\\n' + prevItemComment;\n                    else\n                        prev.comment = prevItemComment;\n                    props.comment = props.comment.substring(prevItemComment.length + 1);\n                }\n            }\n        }\n        if (!isMap && !sep && !props.found) {\n            // item is a value in a seq\n            // → key & sep are empty, start does not include ? or :\n            const valueNode = value\n                ? composeNode(ctx, value, props, onError)\n                : composeEmptyNode(ctx, props.end, sep, null, props, onError);\n            coll.items.push(valueNode);\n            offset = valueNode.range[2];\n            if (isBlock(value))\n                onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n        }\n        else {\n            // item is a key+value pair\n            // key value\n            ctx.atKey = true;\n            const keyStart = props.end;\n            const keyNode = key\n                ? composeNode(ctx, key, props, onError)\n                : composeEmptyNode(ctx, keyStart, start, null, props, onError);\n            if (isBlock(key))\n                onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            ctx.atKey = false;\n            // value properties\n            const valueProps = resolveProps.resolveProps(sep ?? [], {\n                flow: fcName,\n                indicator: 'map-value-ind',\n                next: value,\n                offset: keyNode.range[2],\n                onError,\n                parentIndent: fc.indent,\n                startOnNewline: false\n            });\n            if (valueProps.found) {\n                if (!isMap && !props.found && ctx.options.strict) {\n                    if (sep)\n                        for (const st of sep) {\n                            if (st === valueProps.found)\n                                break;\n                            if (st.type === 'newline') {\n                                onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n                                break;\n                            }\n                        }\n                    if (props.start < valueProps.found.offset - 1024)\n                        onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');\n                }\n            }\n            else if (value) {\n                if ('source' in value && value.source?.[0] === ':')\n                    onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);\n                else\n                    onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : valueProps.found\n                    ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)\n                    : null;\n            if (valueNode) {\n                if (isBlock(value))\n                    onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            }\n            else if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair.Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            if (isMap) {\n                const map = coll;\n                if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n                    onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n                map.items.push(pair);\n            }\n            else {\n                const map = new YAMLMap.YAMLMap(ctx.schema);\n                map.flow = true;\n                map.items.push(pair);\n                const endRange = (valueNode ?? keyNode).range;\n                map.range = [keyNode.range[0], endRange[1], endRange[2]];\n                coll.items.push(map);\n            }\n            offset = valueNode ? valueNode.range[2] : valueProps.end;\n        }\n    }\n    const expectedEnd = isMap ? '}' : ']';\n    const [ce, ...ee] = fc.end;\n    let cePos = offset;\n    if (ce?.source === expectedEnd)\n        cePos = ce.offset + ce.source.length;\n    else {\n        const name = fcName[0].toUpperCase() + fcName.substring(1);\n        const msg = atRoot\n            ? `${name} must end with a ${expectedEnd}`\n            : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;\n        onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);\n        if (ce && ce.source.length !== 1)\n            ee.unshift(ce);\n    }\n    if (ee.length > 0) {\n        const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);\n        if (end.comment) {\n            if (coll.comment)\n                coll.comment += '\\n' + end.comment;\n            else\n                coll.comment = end.comment;\n        }\n        coll.range = [fc.offset, cePos, end.offset];\n    }\n    else {\n        coll.range = [fc.offset, cePos, cePos];\n    }\n    return coll;\n}\n\nexports.resolveFlowCollection = resolveFlowCollection;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveBlockMap = require('./resolve-block-map.js');\nvar resolveBlockSeq = require('./resolve-block-seq.js');\nvar resolveFlowCollection = require('./resolve-flow-collection.js');\n\nfunction resolveCollection(CN, ctx, token, onError, tagName, tag) {\n    const coll = token.type === 'block-map'\n        ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)\n        : token.type === 'block-seq'\n            ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)\n            : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);\n    const Coll = coll.constructor;\n    // If we got a tagName matching the class, or the tag name is '!',\n    // then use the tagName from the node class used to create it.\n    if (tagName === '!' || tagName === Coll.tagName) {\n        coll.tag = Coll.tagName;\n        return coll;\n    }\n    if (tagName)\n        coll.tag = tagName;\n    return coll;\n}\nfunction composeCollection(CN, ctx, token, props, onError) {\n    const tagToken = props.tag;\n    const tagName = !tagToken\n        ? null\n        : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));\n    if (token.type === 'block-seq') {\n        const { anchor, newlineAfterProp: nl } = props;\n        const lastProp = anchor && tagToken\n            ? anchor.offset > tagToken.offset\n                ? anchor\n                : tagToken\n            : (anchor ?? tagToken);\n        if (lastProp && (!nl || nl.offset < lastProp.offset)) {\n            const message = 'Missing newline after block sequence props';\n            onError(lastProp, 'MISSING_CHAR', message);\n        }\n    }\n    const expType = token.type === 'block-map'\n        ? 'map'\n        : token.type === 'block-seq'\n            ? 'seq'\n            : token.start.source === '{'\n                ? 'map'\n                : 'seq';\n    // shortcut: check if it's a generic YAMLMap or YAMLSeq\n    // before jumping into the custom tag logic.\n    if (!tagToken ||\n        !tagName ||\n        tagName === '!' ||\n        (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||\n        (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) {\n        return resolveCollection(CN, ctx, token, onError, tagName);\n    }\n    let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);\n    if (!tag) {\n        const kt = ctx.schema.knownTags[tagName];\n        if (kt?.collection === expType) {\n            ctx.schema.tags.push(Object.assign({}, kt, { default: false }));\n            tag = kt;\n        }\n        else {\n            if (kt) {\n                onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);\n            }\n            else {\n                onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);\n            }\n            return resolveCollection(CN, ctx, token, onError, tagName);\n        }\n    }\n    const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);\n    const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;\n    const node = identity.isNode(res)\n        ? res\n        : new Scalar.Scalar(res);\n    node.range = coll.range;\n    node.tag = tagName;\n    if (tag?.format)\n        node.format = tag.format;\n    return node;\n}\n\nexports.composeCollection = composeCollection;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\n\nfunction resolveBlockScalar(ctx, scalar, onError) {\n    const start = scalar.offset;\n    const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);\n    if (!header)\n        return { value: '', type: null, comment: '', range: [start, start, start] };\n    const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;\n    const lines = scalar.source ? splitLines(scalar.source) : [];\n    // determine the end of content & start of chomping\n    let chompStart = lines.length;\n    for (let i = lines.length - 1; i >= 0; --i) {\n        const content = lines[i][1];\n        if (content === '' || content === '\\r')\n            chompStart = i;\n        else\n            break;\n    }\n    // shortcut for empty contents\n    if (chompStart === 0) {\n        const value = header.chomp === '+' && lines.length > 0\n            ? '\\n'.repeat(Math.max(1, lines.length - 1))\n            : '';\n        let end = start + header.length;\n        if (scalar.source)\n            end += scalar.source.length;\n        return { value, type, comment: header.comment, range: [start, end, end] };\n    }\n    // find the indentation level to trim from start\n    let trimIndent = scalar.indent + header.indent;\n    let offset = scalar.offset + header.length;\n    let contentStart = 0;\n    for (let i = 0; i < chompStart; ++i) {\n        const [indent, content] = lines[i];\n        if (content === '' || content === '\\r') {\n            if (header.indent === 0 && indent.length > trimIndent)\n                trimIndent = indent.length;\n        }\n        else {\n            if (indent.length < trimIndent) {\n                const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';\n                onError(offset + indent.length, 'MISSING_CHAR', message);\n            }\n            if (header.indent === 0)\n                trimIndent = indent.length;\n            contentStart = i;\n            if (trimIndent === 0 && !ctx.atRoot) {\n                const message = 'Block scalar values in collections must be indented';\n                onError(offset, 'BAD_INDENT', message);\n            }\n            break;\n        }\n        offset += indent.length + content.length + 1;\n    }\n    // include trailing more-indented empty lines in content\n    for (let i = lines.length - 1; i >= chompStart; --i) {\n        if (lines[i][0].length > trimIndent)\n            chompStart = i + 1;\n    }\n    let value = '';\n    let sep = '';\n    let prevMoreIndented = false;\n    // leading whitespace is kept intact\n    for (let i = 0; i < contentStart; ++i)\n        value += lines[i][0].slice(trimIndent) + '\\n';\n    for (let i = contentStart; i < chompStart; ++i) {\n        let [indent, content] = lines[i];\n        offset += indent.length + content.length + 1;\n        const crlf = content[content.length - 1] === '\\r';\n        if (crlf)\n            content = content.slice(0, -1);\n        /* istanbul ignore if already caught in lexer */\n        if (content && indent.length < trimIndent) {\n            const src = header.indent\n                ? 'explicit indentation indicator'\n                : 'first line';\n            const message = `Block scalar lines must not be less indented than their ${src}`;\n            onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);\n            indent = '';\n        }\n        if (type === Scalar.Scalar.BLOCK_LITERAL) {\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n        }\n        else if (indent.length > trimIndent || content[0] === '\\t') {\n            // more-indented content within a folded block\n            if (sep === ' ')\n                sep = '\\n';\n            else if (!prevMoreIndented && sep === '\\n')\n                sep = '\\n\\n';\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n            prevMoreIndented = true;\n        }\n        else if (content === '') {\n            // empty line\n            if (sep === '\\n')\n                value += '\\n';\n            else\n                sep = '\\n';\n        }\n        else {\n            value += sep + content;\n            sep = ' ';\n            prevMoreIndented = false;\n        }\n    }\n    switch (header.chomp) {\n        case '-':\n            break;\n        case '+':\n            for (let i = chompStart; i < lines.length; ++i)\n                value += '\\n' + lines[i][0].slice(trimIndent);\n            if (value[value.length - 1] !== '\\n')\n                value += '\\n';\n            break;\n        default:\n            value += '\\n';\n    }\n    const end = start + header.length + scalar.source.length;\n    return { value, type, comment: header.comment, range: [start, end, end] };\n}\nfunction parseBlockScalarHeader({ offset, props }, strict, onError) {\n    /* istanbul ignore if should not happen */\n    if (props[0].type !== 'block-scalar-header') {\n        onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');\n        return null;\n    }\n    const { source } = props[0];\n    const mode = source[0];\n    let indent = 0;\n    let chomp = '';\n    let error = -1;\n    for (let i = 1; i < source.length; ++i) {\n        const ch = source[i];\n        if (!chomp && (ch === '-' || ch === '+'))\n            chomp = ch;\n        else {\n            const n = Number(ch);\n            if (!indent && n)\n                indent = n;\n            else if (error === -1)\n                error = offset + i;\n        }\n    }\n    if (error !== -1)\n        onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);\n    let hasSpace = false;\n    let comment = '';\n    let length = source.length;\n    for (let i = 1; i < props.length; ++i) {\n        const token = props[i];\n        switch (token.type) {\n            case 'space':\n                hasSpace = true;\n            // fallthrough\n            case 'newline':\n                length += token.source.length;\n                break;\n            case 'comment':\n                if (strict && !hasSpace) {\n                    const message = 'Comments must be separated from other tokens by white space characters';\n                    onError(token, 'MISSING_CHAR', message);\n                }\n                length += token.source.length;\n                comment = token.source.substring(1);\n                break;\n            case 'error':\n                onError(token, 'UNEXPECTED_TOKEN', token.message);\n                length += token.source.length;\n                break;\n            /* istanbul ignore next should not happen */\n            default: {\n                const message = `Unexpected token in block scalar header: ${token.type}`;\n                onError(token, 'UNEXPECTED_TOKEN', message);\n                const ts = token.source;\n                if (ts && typeof ts === 'string')\n                    length += ts.length;\n            }\n        }\n    }\n    return { mode, indent, chomp, comment, length };\n}\n/** @returns Array of lines split up as `[indent, content]` */\nfunction splitLines(source) {\n    const split = source.split(/\\n( *)/);\n    const first = split[0];\n    const m = first.match(/^( *)/);\n    const line0 = m?.[1]\n        ? [m[1], first.slice(m[1].length)]\n        : ['', first];\n    const lines = [line0];\n    for (let i = 1; i < split.length; i += 2)\n        lines.push([split[i], split[i + 1]]);\n    return lines;\n}\n\nexports.resolveBlockScalar = resolveBlockScalar;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction resolveFlowScalar(scalar, strict, onError) {\n    const { offset, type, source, end } = scalar;\n    let _type;\n    let value;\n    const _onError = (rel, code, msg) => onError(offset + rel, code, msg);\n    switch (type) {\n        case 'scalar':\n            _type = Scalar.Scalar.PLAIN;\n            value = plainValue(source, _onError);\n            break;\n        case 'single-quoted-scalar':\n            _type = Scalar.Scalar.QUOTE_SINGLE;\n            value = singleQuotedValue(source, _onError);\n            break;\n        case 'double-quoted-scalar':\n            _type = Scalar.Scalar.QUOTE_DOUBLE;\n            value = doubleQuotedValue(source, _onError);\n            break;\n        /* istanbul ignore next should not happen */\n        default:\n            onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);\n            return {\n                value: '',\n                type: null,\n                comment: '',\n                range: [offset, offset + source.length, offset + source.length]\n            };\n    }\n    const valueEnd = offset + source.length;\n    const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);\n    return {\n        value,\n        type: _type,\n        comment: re.comment,\n        range: [offset, valueEnd, re.offset]\n    };\n}\nfunction plainValue(source, onError) {\n    let badChar = '';\n    switch (source[0]) {\n        /* istanbul ignore next should not happen */\n        case '\\t':\n            badChar = 'a tab character';\n            break;\n        case ',':\n            badChar = 'flow indicator character ,';\n            break;\n        case '%':\n            badChar = 'directive indicator character %';\n            break;\n        case '|':\n        case '>': {\n            badChar = `block scalar indicator ${source[0]}`;\n            break;\n        }\n        case '@':\n        case '`': {\n            badChar = `reserved character ${source[0]}`;\n            break;\n        }\n    }\n    if (badChar)\n        onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);\n    return foldLines(source);\n}\nfunction singleQuotedValue(source, onError) {\n    if (source[source.length - 1] !== \"'\" || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', \"Missing closing 'quote\");\n    return foldLines(source.slice(1, -1)).replace(/''/g, \"'\");\n}\nfunction foldLines(source) {\n    /**\n     * The negative lookbehind here and in the `re` RegExp is to\n     * prevent causing a polynomial search time in certain cases.\n     *\n     * The try-catch is for Safari, which doesn't support this yet:\n     * https://caniuse.com/js-regexp-lookbehind\n     */\n    let first, line;\n    try {\n        first = new RegExp('(.*?)(?<![ \\t])[ \\t]*\\r?\\n', 'sy');\n        line = new RegExp('[ \\t]*(.*?)(?:(?<![ \\t])[ \\t]*)?\\r?\\n', 'sy');\n    }\n    catch {\n        first = /(.*?)[ \\t]*\\r?\\n/sy;\n        line = /[ \\t]*(.*?)[ \\t]*\\r?\\n/sy;\n    }\n    let match = first.exec(source);\n    if (!match)\n        return source;\n    let res = match[1];\n    let sep = ' ';\n    let pos = first.lastIndex;\n    line.lastIndex = pos;\n    while ((match = line.exec(source))) {\n        if (match[1] === '') {\n            if (sep === '\\n')\n                res += sep;\n            else\n                sep = '\\n';\n        }\n        else {\n            res += sep + match[1];\n            sep = ' ';\n        }\n        pos = line.lastIndex;\n    }\n    const last = /[ \\t]*(.*)/sy;\n    last.lastIndex = pos;\n    match = last.exec(source);\n    return res + sep + (match?.[1] ?? '');\n}\nfunction doubleQuotedValue(source, onError) {\n    let res = '';\n    for (let i = 1; i < source.length - 1; ++i) {\n        const ch = source[i];\n        if (ch === '\\r' && source[i + 1] === '\\n')\n            continue;\n        if (ch === '\\n') {\n            const { fold, offset } = foldNewline(source, i);\n            res += fold;\n            i = offset;\n        }\n        else if (ch === '\\\\') {\n            let next = source[++i];\n            const cc = escapeCodes[next];\n            if (cc)\n                res += cc;\n            else if (next === '\\n') {\n                // skip escaped newlines, but still trim the following line\n                next = source[i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === '\\r' && source[i + 1] === '\\n') {\n                // skip escaped CRLF newlines, but still trim the following line\n                next = source[++i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === 'x' || next === 'u' || next === 'U') {\n                const length = next === 'x' ? 2 : next === 'u' ? 4 : 8;\n                res += parseCharCode(source, i + 1, length, onError);\n                i += length;\n            }\n            else {\n                const raw = source.substr(i - 1, 2);\n                onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n                res += raw;\n            }\n        }\n        else if (ch === ' ' || ch === '\\t') {\n            // trim trailing whitespace\n            const wsStart = i;\n            let next = source[i + 1];\n            while (next === ' ' || next === '\\t')\n                next = source[++i + 1];\n            if (next !== '\\n' && !(next === '\\r' && source[i + 2] === '\\n'))\n                res += i > wsStart ? source.slice(wsStart, i + 1) : ch;\n        }\n        else {\n            res += ch;\n        }\n    }\n    if (source[source.length - 1] !== '\"' || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', 'Missing closing \"quote');\n    return res;\n}\n/**\n * Fold a single newline into a space, multiple newlines to N - 1 newlines.\n * Presumes `source[offset] === '\\n'`\n */\nfunction foldNewline(source, offset) {\n    let fold = '';\n    let ch = source[offset + 1];\n    while (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n        if (ch === '\\r' && source[offset + 2] !== '\\n')\n            break;\n        if (ch === '\\n')\n            fold += '\\n';\n        offset += 1;\n        ch = source[offset + 1];\n    }\n    if (!fold)\n        fold = ' ';\n    return { fold, offset };\n}\nconst escapeCodes = {\n    '0': '\\0', // null character\n    a: '\\x07', // bell character\n    b: '\\b', // backspace\n    e: '\\x1b', // escape character\n    f: '\\f', // form feed\n    n: '\\n', // line feed\n    r: '\\r', // carriage return\n    t: '\\t', // horizontal tab\n    v: '\\v', // vertical tab\n    N: '\\u0085', // Unicode next line\n    _: '\\u00a0', // Unicode non-breaking space\n    L: '\\u2028', // Unicode line separator\n    P: '\\u2029', // Unicode paragraph separator\n    ' ': ' ',\n    '\"': '\"',\n    '/': '/',\n    '\\\\': '\\\\',\n    '\\t': '\\t'\n};\nfunction parseCharCode(source, offset, length, onError) {\n    const cc = source.substr(offset, length);\n    const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);\n    const code = ok ? parseInt(cc, 16) : NaN;\n    try {\n        return String.fromCodePoint(code);\n    }\n    catch {\n        const raw = source.substr(offset - 2, length + 2);\n        onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n        return raw;\n    }\n}\n\nexports.resolveFlowScalar = resolveFlowScalar;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveBlockScalar = require('./resolve-block-scalar.js');\nvar resolveFlowScalar = require('./resolve-flow-scalar.js');\n\nfunction composeScalar(ctx, token, tagToken, onError) {\n    const { value, type, comment, range } = token.type === 'block-scalar'\n        ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError)\n        : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);\n    const tagName = tagToken\n        ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))\n        : null;\n    let tag;\n    if (ctx.options.stringKeys && ctx.atKey) {\n        tag = ctx.schema[identity.SCALAR];\n    }\n    else if (tagName)\n        tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);\n    else if (token.type === 'scalar')\n        tag = findScalarTagByTest(ctx, value, token, onError);\n    else\n        tag = ctx.schema[identity.SCALAR];\n    let scalar;\n    try {\n        const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);\n        scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);\n    }\n    catch (error) {\n        const msg = error instanceof Error ? error.message : String(error);\n        onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);\n        scalar = new Scalar.Scalar(value);\n    }\n    scalar.range = range;\n    scalar.source = value;\n    if (type)\n        scalar.type = type;\n    if (tagName)\n        scalar.tag = tagName;\n    if (tag.format)\n        scalar.format = tag.format;\n    if (comment)\n        scalar.comment = comment;\n    return scalar;\n}\nfunction findScalarTagByName(schema, value, tagName, tagToken, onError) {\n    if (tagName === '!')\n        return schema[identity.SCALAR]; // non-specific tag\n    const matchWithTest = [];\n    for (const tag of schema.tags) {\n        if (!tag.collection && tag.tag === tagName) {\n            if (tag.default && tag.test)\n                matchWithTest.push(tag);\n            else\n                return tag;\n        }\n    }\n    for (const tag of matchWithTest)\n        if (tag.test?.test(value))\n            return tag;\n    const kt = schema.knownTags[tagName];\n    if (kt && !kt.collection) {\n        // Ensure that the known tag is available for stringifying,\n        // but does not get used by default.\n        schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));\n        return kt;\n    }\n    onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');\n    return schema[identity.SCALAR];\n}\nfunction findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {\n    const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&\n        tag.test?.test(value)) || schema[identity.SCALAR];\n    if (schema.compat) {\n        const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??\n            schema[identity.SCALAR];\n        if (tag.tag !== compat.tag) {\n            const ts = directives.tagString(tag.tag);\n            const cs = directives.tagString(compat.tag);\n            const msg = `Value may be parsed as either ${ts} or ${cs}`;\n            onError(token, 'TAG_RESOLVE_FAILED', msg, true);\n        }\n    }\n    return tag;\n}\n\nexports.composeScalar = composeScalar;\n","'use strict';\n\nfunction emptyScalarPosition(offset, before, pos) {\n    if (before) {\n        pos ?? (pos = before.length);\n        for (let i = pos - 1; i >= 0; --i) {\n            let st = before[i];\n            switch (st.type) {\n                case 'space':\n                case 'comment':\n                case 'newline':\n                    offset -= st.source.length;\n                    continue;\n            }\n            // Technically, an empty scalar is immediately after the last non-empty\n            // node, but it's more useful to place it after any whitespace.\n            st = before[++i];\n            while (st?.type === 'space') {\n                offset += st.source.length;\n                st = before[++i];\n            }\n            break;\n        }\n    }\n    return offset;\n}\n\nexports.emptyScalarPosition = emptyScalarPosition;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar composeCollection = require('./compose-collection.js');\nvar composeScalar = require('./compose-scalar.js');\nvar resolveEnd = require('./resolve-end.js');\nvar utilEmptyScalarPosition = require('./util-empty-scalar-position.js');\n\nconst CN = { composeNode, composeEmptyNode };\nfunction composeNode(ctx, token, props, onError) {\n    const atKey = ctx.atKey;\n    const { spaceBefore, comment, anchor, tag } = props;\n    let node;\n    let isSrcToken = true;\n    switch (token.type) {\n        case 'alias':\n            node = composeAlias(ctx, token, onError);\n            if (anchor || tag)\n                onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');\n            break;\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'block-scalar':\n            node = composeScalar.composeScalar(ctx, token, tag, onError);\n            if (anchor)\n                node.anchor = anchor.source.substring(1);\n            break;\n        case 'block-map':\n        case 'block-seq':\n        case 'flow-collection':\n            try {\n                node = composeCollection.composeCollection(CN, ctx, token, props, onError);\n                if (anchor)\n                    node.anchor = anchor.source.substring(1);\n            }\n            catch (error) {\n                // Almost certainly here due to a stack overflow\n                const message = error instanceof Error ? error.message : String(error);\n                onError(token, 'RESOURCE_EXHAUSTION', message);\n            }\n            break;\n        default: {\n            const message = token.type === 'error'\n                ? token.message\n                : `Unsupported token (type: ${token.type})`;\n            onError(token, 'UNEXPECTED_TOKEN', message);\n            isSrcToken = false;\n        }\n    }\n    node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));\n    if (anchor && node.anchor === '')\n        onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    if (atKey &&\n        ctx.options.stringKeys &&\n        (!identity.isScalar(node) ||\n            typeof node.value !== 'string' ||\n            (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {\n        const msg = 'With stringKeys, all keys must be strings';\n        onError(tag ?? token, 'NON_STRING_KEY', msg);\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        if (token.type === 'scalar' && token.source === '')\n            node.comment = comment;\n        else\n            node.commentBefore = comment;\n    }\n    // @ts-expect-error Type checking misses meaning of isSrcToken\n    if (ctx.options.keepSourceTokens && isSrcToken)\n        node.srcToken = token;\n    return node;\n}\nfunction composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {\n    const token = {\n        type: 'scalar',\n        offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),\n        indent: -1,\n        source: ''\n    };\n    const node = composeScalar.composeScalar(ctx, token, tag, onError);\n    if (anchor) {\n        node.anchor = anchor.source.substring(1);\n        if (node.anchor === '')\n            onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        node.comment = comment;\n        node.range[2] = end;\n    }\n    return node;\n}\nfunction composeAlias({ options }, { offset, source, end }, onError) {\n    const alias = new Alias.Alias(source.substring(1));\n    if (alias.source === '')\n        onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');\n    if (alias.source.endsWith(':'))\n        onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);\n    const valueEnd = offset + source.length;\n    const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);\n    alias.range = [offset, valueEnd, re.offset];\n    if (re.comment)\n        alias.comment = re.comment;\n    return alias;\n}\n\nexports.composeEmptyNode = composeEmptyNode;\nexports.composeNode = composeNode;\n","'use strict';\n\nvar Document = require('../doc/Document.js');\nvar composeNode = require('./compose-node.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\n\nfunction composeDoc(options, directives, { offset, start, value, end }, onError) {\n    const opts = Object.assign({ _directives: directives }, options);\n    const doc = new Document.Document(undefined, opts);\n    const ctx = {\n        atKey: false,\n        atRoot: true,\n        directives: doc.directives,\n        options: doc.options,\n        schema: doc.schema\n    };\n    const props = resolveProps.resolveProps(start, {\n        indicator: 'doc-start',\n        next: value ?? end?.[0],\n        offset,\n        onError,\n        parentIndent: 0,\n        startOnNewline: true\n    });\n    if (props.found) {\n        doc.directives.docStart = true;\n        if (value &&\n            (value.type === 'block-map' || value.type === 'block-seq') &&\n            !props.hasNewline)\n            onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');\n    }\n    // @ts-expect-error If Contents is set, let's trust the user\n    doc.contents = value\n        ? composeNode.composeNode(ctx, value, props, onError)\n        : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);\n    const contentEnd = doc.contents.range[2];\n    const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);\n    if (re.comment)\n        doc.comment = re.comment;\n    doc.range = [offset, contentEnd, re.offset];\n    return doc;\n}\n\nexports.composeDoc = composeDoc;\n","'use strict';\n\nvar node_process = require('process');\nvar directives = require('../doc/directives.js');\nvar Document = require('../doc/Document.js');\nvar errors = require('../errors.js');\nvar identity = require('../nodes/identity.js');\nvar composeDoc = require('./compose-doc.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction getErrorPos(src) {\n    if (typeof src === 'number')\n        return [src, src + 1];\n    if (Array.isArray(src))\n        return src.length === 2 ? src : [src[0], src[1]];\n    const { offset, source } = src;\n    return [offset, offset + (typeof source === 'string' ? source.length : 1)];\n}\nfunction parsePrelude(prelude) {\n    let comment = '';\n    let atComment = false;\n    let afterEmptyLine = false;\n    for (let i = 0; i < prelude.length; ++i) {\n        const source = prelude[i];\n        switch (source[0]) {\n            case '#':\n                comment +=\n                    (comment === '' ? '' : afterEmptyLine ? '\\n\\n' : '\\n') +\n                        (source.substring(1) || ' ');\n                atComment = true;\n                afterEmptyLine = false;\n                break;\n            case '%':\n                if (prelude[i + 1]?.[0] !== '#')\n                    i += 1;\n                atComment = false;\n                break;\n            default:\n                // This may be wrong after doc-end, but in that case it doesn't matter\n                if (!atComment)\n                    afterEmptyLine = true;\n                atComment = false;\n        }\n    }\n    return { comment, afterEmptyLine };\n}\n/**\n * Compose a stream of CST nodes into a stream of YAML Documents.\n *\n * ```ts\n * import { Composer, Parser } from 'yaml'\n *\n * const src: string = ...\n * const tokens = new Parser().parse(src)\n * const docs = new Composer().compose(tokens)\n * ```\n */\nclass Composer {\n    constructor(options = {}) {\n        this.doc = null;\n        this.atDirectives = false;\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n        this.onError = (source, code, message, warning) => {\n            const pos = getErrorPos(source);\n            if (warning)\n                this.warnings.push(new errors.YAMLWarning(pos, code, message));\n            else\n                this.errors.push(new errors.YAMLParseError(pos, code, message));\n        };\n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        this.directives = new directives.Directives({ version: options.version || '1.2' });\n        this.options = options;\n    }\n    decorate(doc, afterDoc) {\n        const { comment, afterEmptyLine } = parsePrelude(this.prelude);\n        //console.log({ dc: doc.comment, prelude, comment })\n        if (comment) {\n            const dc = doc.contents;\n            if (afterDoc) {\n                doc.comment = doc.comment ? `${doc.comment}\\n${comment}` : comment;\n            }\n            else if (afterEmptyLine || doc.directives.docStart || !dc) {\n                doc.commentBefore = comment;\n            }\n            else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {\n                let it = dc.items[0];\n                if (identity.isPair(it))\n                    it = it.key;\n                const cb = it.commentBefore;\n                it.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n            else {\n                const cb = dc.commentBefore;\n                dc.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n        }\n        if (afterDoc) {\n            for (let i = 0; i < this.errors.length; ++i)\n                doc.errors.push(this.errors[i]);\n            for (let i = 0; i < this.warnings.length; ++i)\n                doc.warnings.push(this.warnings[i]);\n        }\n        else {\n            doc.errors = this.errors;\n            doc.warnings = this.warnings;\n        }\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n    }\n    /**\n     * Current stream status information.\n     *\n     * Mostly useful at the end of input for an empty stream.\n     */\n    streamInfo() {\n        return {\n            comment: parsePrelude(this.prelude).comment,\n            directives: this.directives,\n            errors: this.errors,\n            warnings: this.warnings\n        };\n    }\n    /**\n     * Compose tokens into documents.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *compose(tokens, forceDoc = false, endOffset = -1) {\n        for (const token of tokens)\n            yield* this.next(token);\n        yield* this.end(forceDoc, endOffset);\n    }\n    /** Advance the composer by one CST token. */\n    *next(token) {\n        if (node_process.env.LOG_STREAM)\n            console.dir(token, { depth: null });\n        switch (token.type) {\n            case 'directive':\n                this.directives.add(token.source, (offset, message, warning) => {\n                    const pos = getErrorPos(token);\n                    pos[0] += offset;\n                    this.onError(pos, 'BAD_DIRECTIVE', message, warning);\n                });\n                this.prelude.push(token.source);\n                this.atDirectives = true;\n                break;\n            case 'document': {\n                const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);\n                if (this.atDirectives && !doc.directives.docStart)\n                    this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');\n                this.decorate(doc, false);\n                if (this.doc)\n                    yield this.doc;\n                this.doc = doc;\n                this.atDirectives = false;\n                break;\n            }\n            case 'byte-order-mark':\n            case 'space':\n                break;\n            case 'comment':\n            case 'newline':\n                this.prelude.push(token.source);\n                break;\n            case 'error': {\n                const msg = token.source\n                    ? `${token.message}: ${JSON.stringify(token.source)}`\n                    : token.message;\n                const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);\n                if (this.atDirectives || !this.doc)\n                    this.errors.push(error);\n                else\n                    this.doc.errors.push(error);\n                break;\n            }\n            case 'doc-end': {\n                if (!this.doc) {\n                    const msg = 'Unexpected doc-end without preceding document';\n                    this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));\n                    break;\n                }\n                this.doc.directives.docEnd = true;\n                const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);\n                this.decorate(this.doc, true);\n                if (end.comment) {\n                    const dc = this.doc.comment;\n                    this.doc.comment = dc ? `${dc}\\n${end.comment}` : end.comment;\n                }\n                this.doc.range[2] = end.offset;\n                break;\n            }\n            default:\n                this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));\n        }\n    }\n    /**\n     * Call at end of input to yield any remaining document.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *end(forceDoc = false, endOffset = -1) {\n        if (this.doc) {\n            this.decorate(this.doc, true);\n            yield this.doc;\n            this.doc = null;\n        }\n        else if (forceDoc) {\n            const opts = Object.assign({ _directives: this.directives }, this.options);\n            const doc = new Document.Document(undefined, opts);\n            if (this.atDirectives)\n                this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');\n            doc.range = [0, endOffset, endOffset];\n            this.decorate(doc, false);\n            yield doc;\n        }\n    }\n}\n\nexports.Composer = Composer;\n","'use strict';\n\nvar resolveBlockScalar = require('../compose/resolve-block-scalar.js');\nvar resolveFlowScalar = require('../compose/resolve-flow-scalar.js');\nvar errors = require('../errors.js');\nvar stringifyString = require('../stringify/stringifyString.js');\n\nfunction resolveAsScalar(token, strict = true, onError) {\n    if (token) {\n        const _onError = (pos, code, message) => {\n            const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;\n            if (onError)\n                onError(offset, code, message);\n            else\n                throw new errors.YAMLParseError([offset, offset + 1], code, message);\n        };\n        switch (token.type) {\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);\n            case 'block-scalar':\n                return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);\n        }\n    }\n    return null;\n}\n/**\n * Create a new scalar token with `value`\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.indent The indent level of the token.\n * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.\n * @param context.offset The offset position of the token.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction createScalarToken(value, context) {\n    const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;\n    const source = stringifyString.stringifyString({ type, value }, {\n        implicitKey,\n        indent: indent > 0 ? ' '.repeat(indent) : '',\n        inFlow,\n        options: { blockQuote: true, lineWidth: -1 }\n    });\n    const end = context.end ?? [\n        { type: 'newline', offset: -1, indent, source: '\\n' }\n    ];\n    switch (source[0]) {\n        case '|':\n        case '>': {\n            const he = source.indexOf('\\n');\n            const head = source.substring(0, he);\n            const body = source.substring(he + 1) + '\\n';\n            const props = [\n                { type: 'block-scalar-header', offset, indent, source: head }\n            ];\n            if (!addEndtoBlockProps(props, end))\n                props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n            return { type: 'block-scalar', offset, indent, props, source: body };\n        }\n        case '\"':\n            return { type: 'double-quoted-scalar', offset, indent, source, end };\n        case \"'\":\n            return { type: 'single-quoted-scalar', offset, indent, source, end };\n        default:\n            return { type: 'scalar', offset, indent, source, end };\n    }\n}\n/**\n * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.\n *\n * Best efforts are made to retain any comments previously associated with the `token`,\n * though all contents within a collection's `items` will be overwritten.\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.afterKey In most cases, values after a key should have an additional level of indentation.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction setScalarValue(token, value, context = {}) {\n    let { afterKey = false, implicitKey = false, inFlow = false, type } = context;\n    let indent = 'indent' in token ? token.indent : null;\n    if (afterKey && typeof indent === 'number')\n        indent += 2;\n    if (!type)\n        switch (token.type) {\n            case 'single-quoted-scalar':\n                type = 'QUOTE_SINGLE';\n                break;\n            case 'double-quoted-scalar':\n                type = 'QUOTE_DOUBLE';\n                break;\n            case 'block-scalar': {\n                const header = token.props[0];\n                if (header.type !== 'block-scalar-header')\n                    throw new Error('Invalid block scalar header');\n                type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';\n                break;\n            }\n            default:\n                type = 'PLAIN';\n        }\n    const source = stringifyString.stringifyString({ type, value }, {\n        implicitKey: implicitKey || indent === null,\n        indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',\n        inFlow,\n        options: { blockQuote: true, lineWidth: -1 }\n    });\n    switch (source[0]) {\n        case '|':\n        case '>':\n            setBlockScalarValue(token, source);\n            break;\n        case '\"':\n            setFlowScalarValue(token, source, 'double-quoted-scalar');\n            break;\n        case \"'\":\n            setFlowScalarValue(token, source, 'single-quoted-scalar');\n            break;\n        default:\n            setFlowScalarValue(token, source, 'scalar');\n    }\n}\nfunction setBlockScalarValue(token, source) {\n    const he = source.indexOf('\\n');\n    const head = source.substring(0, he);\n    const body = source.substring(he + 1) + '\\n';\n    if (token.type === 'block-scalar') {\n        const header = token.props[0];\n        if (header.type !== 'block-scalar-header')\n            throw new Error('Invalid block scalar header');\n        header.source = head;\n        token.source = body;\n    }\n    else {\n        const { offset } = token;\n        const indent = 'indent' in token ? token.indent : -1;\n        const props = [\n            { type: 'block-scalar-header', offset, indent, source: head }\n        ];\n        if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))\n            props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n        for (const key of Object.keys(token))\n            if (key !== 'type' && key !== 'offset')\n                delete token[key];\n        Object.assign(token, { type: 'block-scalar', indent, props, source: body });\n    }\n}\n/** @returns `true` if last token is a newline */\nfunction addEndtoBlockProps(props, end) {\n    if (end)\n        for (const st of end)\n            switch (st.type) {\n                case 'space':\n                case 'comment':\n                    props.push(st);\n                    break;\n                case 'newline':\n                    props.push(st);\n                    return true;\n            }\n    return false;\n}\nfunction setFlowScalarValue(token, source, type) {\n    switch (token.type) {\n        case 'scalar':\n        case 'double-quoted-scalar':\n        case 'single-quoted-scalar':\n            token.type = type;\n            token.source = source;\n            break;\n        case 'block-scalar': {\n            const end = token.props.slice(1);\n            let oa = source.length;\n            if (token.props[0].type === 'block-scalar-header')\n                oa -= token.props[0].source.length;\n            for (const tok of end)\n                tok.offset += oa;\n            delete token.props;\n            Object.assign(token, { type, source, end });\n            break;\n        }\n        case 'block-map':\n        case 'block-seq': {\n            const offset = token.offset + source.length;\n            const nl = { type: 'newline', offset, indent: token.indent, source: '\\n' };\n            delete token.items;\n            Object.assign(token, { type, source, end: [nl] });\n            break;\n        }\n        default: {\n            const indent = 'indent' in token ? token.indent : -1;\n            const end = 'end' in token && Array.isArray(token.end)\n                ? token.end.filter(st => st.type === 'space' ||\n                    st.type === 'comment' ||\n                    st.type === 'newline')\n                : [];\n            for (const key of Object.keys(token))\n                if (key !== 'type' && key !== 'offset')\n                    delete token[key];\n            Object.assign(token, { type, indent, source, end });\n        }\n    }\n}\n\nexports.createScalarToken = createScalarToken;\nexports.resolveAsScalar = resolveAsScalar;\nexports.setScalarValue = setScalarValue;\n","'use strict';\n\n/**\n * Stringify a CST document, token, or collection item\n *\n * Fair warning: This applies no validation whatsoever, and\n * simply concatenates the sources in their logical order.\n */\nconst stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);\nfunction stringifyToken(token) {\n    switch (token.type) {\n        case 'block-scalar': {\n            let res = '';\n            for (const tok of token.props)\n                res += stringifyToken(tok);\n            return res + token.source;\n        }\n        case 'block-map':\n        case 'block-seq': {\n            let res = '';\n            for (const item of token.items)\n                res += stringifyItem(item);\n            return res;\n        }\n        case 'flow-collection': {\n            let res = token.start.source;\n            for (const item of token.items)\n                res += stringifyItem(item);\n            for (const st of token.end)\n                res += st.source;\n            return res;\n        }\n        case 'document': {\n            let res = stringifyItem(token);\n            if (token.end)\n                for (const st of token.end)\n                    res += st.source;\n            return res;\n        }\n        default: {\n            let res = token.source;\n            if ('end' in token && token.end)\n                for (const st of token.end)\n                    res += st.source;\n            return res;\n        }\n    }\n}\nfunction stringifyItem({ start, key, sep, value }) {\n    let res = '';\n    for (const st of start)\n        res += st.source;\n    if (key)\n        res += stringifyToken(key);\n    if (sep)\n        for (const st of sep)\n            res += st.source;\n    if (value)\n        res += stringifyToken(value);\n    return res;\n}\n\nexports.stringify = stringify;\n","'use strict';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove item');\n/**\n * Apply a visitor to a CST document or item.\n *\n * Walks through the tree (depth-first) starting from the root, calling a\n * `visitor` function with two arguments when entering each item:\n *   - `item`: The current item, which included the following members:\n *     - `start: SourceToken[]` – Source tokens before the key or value,\n *       possibly including its anchor or tag.\n *     - `key?: Token | null` – Set for pair values. May then be `null`, if\n *       the key before the `:` separator is empty.\n *     - `sep?: SourceToken[]` – Source tokens between the key and the value,\n *       which should include the `:` map value indicator if `value` is set.\n *     - `value?: Token` – The value of a sequence item, or of a map pair.\n *   - `path`: The steps from the root to the current node, as an array of\n *     `['key' | 'value', number]` tuples.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this token, continue with\n *      next sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current item, then continue with the next one\n *   - `number`: Set the index of the next step. This is useful especially if\n *     the index of the current token has changed.\n *   - `function`: Define the next visitor for this item. After the original\n *     visitor is called on item entry, next visitors are called after handling\n *     a non-empty `key` and when exiting the item.\n */\nfunction visit(cst, visitor) {\n    if ('type' in cst && cst.type === 'document')\n        cst = { start: cst.start, value: cst.value };\n    _visit(Object.freeze([]), cst, visitor);\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current item */\nvisit.SKIP = SKIP;\n/** Remove the current item */\nvisit.REMOVE = REMOVE;\n/** Find the item at `path` from `cst` as the root */\nvisit.itemAtPath = (cst, path) => {\n    let item = cst;\n    for (const [field, index] of path) {\n        const tok = item?.[field];\n        if (tok && 'items' in tok) {\n            item = tok.items[index];\n        }\n        else\n            return undefined;\n    }\n    return item;\n};\n/**\n * Get the immediate parent collection of the item at `path` from `cst` as the root.\n *\n * Throws an error if the collection is not found, which should never happen if the item itself exists.\n */\nvisit.parentCollection = (cst, path) => {\n    const parent = visit.itemAtPath(cst, path.slice(0, -1));\n    const field = path[path.length - 1][0];\n    const coll = parent?.[field];\n    if (coll && 'items' in coll)\n        return coll;\n    throw new Error('Parent collection not found');\n};\nfunction _visit(path, item, visitor) {\n    let ctrl = visitor(item, path);\n    if (typeof ctrl === 'symbol')\n        return ctrl;\n    for (const field of ['key', 'value']) {\n        const token = item[field];\n        if (token && 'items' in token) {\n            for (let i = 0; i < token.items.length; ++i) {\n                const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    token.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n            if (typeof ctrl === 'function' && field === 'key')\n                ctrl = ctrl(item, path);\n        }\n    }\n    return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;\n}\n\nexports.visit = visit;\n","'use strict';\n\nvar cstScalar = require('./cst-scalar.js');\nvar cstStringify = require('./cst-stringify.js');\nvar cstVisit = require('./cst-visit.js');\n\n/** The byte order mark */\nconst BOM = '\\u{FEFF}';\n/** Start of doc-mode */\nconst DOCUMENT = '\\x02'; // C0: Start of Text\n/** Unexpected end of flow-mode */\nconst FLOW_END = '\\x18'; // C0: Cancel\n/** Next token is a scalar value */\nconst SCALAR = '\\x1f'; // C0: Unit Separator\n/** @returns `true` if `token` is a flow or block collection */\nconst isCollection = (token) => !!token && 'items' in token;\n/** @returns `true` if `token` is a flow or block scalar; not an alias */\nconst isScalar = (token) => !!token &&\n    (token.type === 'scalar' ||\n        token.type === 'single-quoted-scalar' ||\n        token.type === 'double-quoted-scalar' ||\n        token.type === 'block-scalar');\n/* istanbul ignore next */\n/** Get a printable representation of a lexer token */\nfunction prettyToken(token) {\n    switch (token) {\n        case BOM:\n            return '<BOM>';\n        case DOCUMENT:\n            return '<DOC>';\n        case FLOW_END:\n            return '<FLOW_END>';\n        case SCALAR:\n            return '<SCALAR>';\n        default:\n            return JSON.stringify(token);\n    }\n}\n/** Identify the type of a lexer token. May return `null` for unknown tokens. */\nfunction tokenType(source) {\n    switch (source) {\n        case BOM:\n            return 'byte-order-mark';\n        case DOCUMENT:\n            return 'doc-mode';\n        case FLOW_END:\n            return 'flow-error-end';\n        case SCALAR:\n            return 'scalar';\n        case '---':\n            return 'doc-start';\n        case '...':\n            return 'doc-end';\n        case '':\n        case '\\n':\n        case '\\r\\n':\n            return 'newline';\n        case '-':\n            return 'seq-item-ind';\n        case '?':\n            return 'explicit-key-ind';\n        case ':':\n            return 'map-value-ind';\n        case '{':\n            return 'flow-map-start';\n        case '}':\n            return 'flow-map-end';\n        case '[':\n            return 'flow-seq-start';\n        case ']':\n            return 'flow-seq-end';\n        case ',':\n            return 'comma';\n    }\n    switch (source[0]) {\n        case ' ':\n        case '\\t':\n            return 'space';\n        case '#':\n            return 'comment';\n        case '%':\n            return 'directive-line';\n        case '*':\n            return 'alias';\n        case '&':\n            return 'anchor';\n        case '!':\n            return 'tag';\n        case \"'\":\n            return 'single-quoted-scalar';\n        case '\"':\n            return 'double-quoted-scalar';\n        case '|':\n        case '>':\n            return 'block-scalar-header';\n    }\n    return null;\n}\n\nexports.createScalarToken = cstScalar.createScalarToken;\nexports.resolveAsScalar = cstScalar.resolveAsScalar;\nexports.setScalarValue = cstScalar.setScalarValue;\nexports.stringify = cstStringify.stringify;\nexports.visit = cstVisit.visit;\nexports.BOM = BOM;\nexports.DOCUMENT = DOCUMENT;\nexports.FLOW_END = FLOW_END;\nexports.SCALAR = SCALAR;\nexports.isCollection = isCollection;\nexports.isScalar = isScalar;\nexports.prettyToken = prettyToken;\nexports.tokenType = tokenType;\n","'use strict';\n\nvar cst = require('./cst.js');\n\n/*\nSTART -> stream\n\nstream\n  directive -> line-end -> stream\n  indent + line-end -> stream\n  [else] -> line-start\n\nline-end\n  comment -> line-end\n  newline -> .\n  input-end -> END\n\nline-start\n  doc-start -> doc\n  doc-end -> stream\n  [else] -> indent -> block-start\n\nblock-start\n  seq-item-start -> block-start\n  explicit-key-start -> block-start\n  map-value-start -> block-start\n  [else] -> doc\n\ndoc\n  line-end -> line-start\n  spaces -> doc\n  anchor -> doc\n  tag -> doc\n  flow-start -> flow -> doc\n  flow-end -> error -> doc\n  seq-item-start -> error -> doc\n  explicit-key-start -> error -> doc\n  map-value-start -> doc\n  alias -> doc\n  quote-start -> quoted-scalar -> doc\n  block-scalar-header -> line-end -> block-scalar(min) -> line-start\n  [else] -> plain-scalar(false, min) -> doc\n\nflow\n  line-end -> flow\n  spaces -> flow\n  anchor -> flow\n  tag -> flow\n  flow-start -> flow -> flow\n  flow-end -> .\n  seq-item-start -> error -> flow\n  explicit-key-start -> flow\n  map-value-start -> flow\n  alias -> flow\n  quote-start -> quoted-scalar -> flow\n  comma -> flow\n  [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n  quote-end -> .\n  [else] -> quoted-scalar\n\nblock-scalar(min)\n  newline + peek(indent < min) -> .\n  [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n  scalar-end(is-flow) -> .\n  peek(newline + (indent < min)) -> .\n  [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n    switch (ch) {\n        case undefined:\n        case ' ':\n        case '\\n':\n        case '\\r':\n        case '\\t':\n            return true;\n        default:\n            return false;\n    }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n    constructor() {\n        /**\n         * Flag indicating whether the end of the current buffer marks the end of\n         * all input\n         */\n        this.atEnd = false;\n        /**\n         * Explicit indent set in block scalar header, as an offset from the current\n         * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n         * explicitly set.\n         */\n        this.blockScalarIndent = -1;\n        /**\n         * Block scalars that include a + (keep) chomping indicator in their header\n         * include trailing empty lines, which are otherwise excluded from the\n         * scalar's contents.\n         */\n        this.blockScalarKeep = false;\n        /** Current input */\n        this.buffer = '';\n        /**\n         * Flag noting whether the map value indicator : can immediately follow this\n         * node within a flow context.\n         */\n        this.flowKey = false;\n        /** Count of surrounding flow collection levels. */\n        this.flowLevel = 0;\n        /**\n         * Minimum level of indentation required for next lines to be parsed as a\n         * part of the current scalar value.\n         */\n        this.indentNext = 0;\n        /** Indentation level of the current line. */\n        this.indentValue = 0;\n        /** Position of the next \\n character. */\n        this.lineEndPos = null;\n        /** Stores the state of the lexer if reaching the end of incpomplete input */\n        this.next = null;\n        /** A pointer to `buffer`; the current position of the lexer. */\n        this.pos = 0;\n    }\n    /**\n     * Generate YAML tokens from the `source` string. If `incomplete`,\n     * a part of the last line may be left as a buffer for the next call.\n     *\n     * @returns A generator of lexical tokens\n     */\n    *lex(source, incomplete = false) {\n        if (source) {\n            if (typeof source !== 'string')\n                throw TypeError('source is not a string');\n            this.buffer = this.buffer ? this.buffer + source : source;\n            this.lineEndPos = null;\n        }\n        this.atEnd = !incomplete;\n        let next = this.next ?? 'stream';\n        while (next && (incomplete || this.hasChars(1)))\n            next = yield* this.parseNext(next);\n    }\n    atLineEnd() {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (ch === ' ' || ch === '\\t')\n            ch = this.buffer[++i];\n        if (!ch || ch === '#' || ch === '\\n')\n            return true;\n        if (ch === '\\r')\n            return this.buffer[i + 1] === '\\n';\n        return false;\n    }\n    charAt(n) {\n        return this.buffer[this.pos + n];\n    }\n    continueScalar(offset) {\n        let ch = this.buffer[offset];\n        if (this.indentNext > 0) {\n            let indent = 0;\n            while (ch === ' ')\n                ch = this.buffer[++indent + offset];\n            if (ch === '\\r') {\n                const next = this.buffer[indent + offset + 1];\n                if (next === '\\n' || (!next && !this.atEnd))\n                    return offset + indent + 1;\n            }\n            return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n                ? offset + indent\n                : -1;\n        }\n        if (ch === '-' || ch === '.') {\n            const dt = this.buffer.substr(offset, 3);\n            if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n                return -1;\n        }\n        return offset;\n    }\n    getLine() {\n        let end = this.lineEndPos;\n        if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n            end = this.buffer.indexOf('\\n', this.pos);\n            this.lineEndPos = end;\n        }\n        if (end === -1)\n            return this.atEnd ? this.buffer.substring(this.pos) : null;\n        if (this.buffer[end - 1] === '\\r')\n            end -= 1;\n        return this.buffer.substring(this.pos, end);\n    }\n    hasChars(n) {\n        return this.pos + n <= this.buffer.length;\n    }\n    setNext(state) {\n        this.buffer = this.buffer.substring(this.pos);\n        this.pos = 0;\n        this.lineEndPos = null;\n        this.next = state;\n        return null;\n    }\n    peek(n) {\n        return this.buffer.substr(this.pos, n);\n    }\n    *parseNext(next) {\n        switch (next) {\n            case 'stream':\n                return yield* this.parseStream();\n            case 'line-start':\n                return yield* this.parseLineStart();\n            case 'block-start':\n                return yield* this.parseBlockStart();\n            case 'doc':\n                return yield* this.parseDocument();\n            case 'flow':\n                return yield* this.parseFlowCollection();\n            case 'quoted-scalar':\n                return yield* this.parseQuotedScalar();\n            case 'block-scalar':\n                return yield* this.parseBlockScalar();\n            case 'plain-scalar':\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseStream() {\n        let line = this.getLine();\n        if (line === null)\n            return this.setNext('stream');\n        if (line[0] === cst.BOM) {\n            yield* this.pushCount(1);\n            line = line.substring(1);\n        }\n        if (line[0] === '%') {\n            let dirEnd = line.length;\n            let cs = line.indexOf('#');\n            while (cs !== -1) {\n                const ch = line[cs - 1];\n                if (ch === ' ' || ch === '\\t') {\n                    dirEnd = cs - 1;\n                    break;\n                }\n                else {\n                    cs = line.indexOf('#', cs + 1);\n                }\n            }\n            while (true) {\n                const ch = line[dirEnd - 1];\n                if (ch === ' ' || ch === '\\t')\n                    dirEnd -= 1;\n                else\n                    break;\n            }\n            const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n            yield* this.pushCount(line.length - n); // possible comment\n            this.pushNewline();\n            return 'stream';\n        }\n        if (this.atLineEnd()) {\n            const sp = yield* this.pushSpaces(true);\n            yield* this.pushCount(line.length - sp);\n            yield* this.pushNewline();\n            return 'stream';\n        }\n        yield cst.DOCUMENT;\n        return yield* this.parseLineStart();\n    }\n    *parseLineStart() {\n        const ch = this.charAt(0);\n        if (!ch && !this.atEnd)\n            return this.setNext('line-start');\n        if (ch === '-' || ch === '.') {\n            if (!this.atEnd && !this.hasChars(4))\n                return this.setNext('line-start');\n            const s = this.peek(3);\n            if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n                yield* this.pushCount(3);\n                this.indentValue = 0;\n                this.indentNext = 0;\n                return s === '---' ? 'doc' : 'stream';\n            }\n        }\n        this.indentValue = yield* this.pushSpaces(false);\n        if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n            this.indentNext = this.indentValue;\n        return yield* this.parseBlockStart();\n    }\n    *parseBlockStart() {\n        const [ch0, ch1] = this.peek(2);\n        if (!ch1 && !this.atEnd)\n            return this.setNext('block-start');\n        if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n            const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n            this.indentNext = this.indentValue + 1;\n            this.indentValue += n;\n            return 'block-start';\n        }\n        return 'doc';\n    }\n    *parseDocument() {\n        yield* this.pushSpaces(true);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('doc');\n        let n = yield* this.pushIndicators();\n        switch (line[n]) {\n            case '#':\n                yield* this.pushCount(line.length - n);\n            // fallthrough\n            case undefined:\n                yield* this.pushNewline();\n                return yield* this.parseLineStart();\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel = 1;\n                return 'flow';\n            case '}':\n            case ']':\n                // this is an error\n                yield* this.pushCount(1);\n                return 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'doc';\n            case '\"':\n            case \"'\":\n                return yield* this.parseQuotedScalar();\n            case '|':\n            case '>':\n                n += yield* this.parseBlockScalarHeader();\n                n += yield* this.pushSpaces(true);\n                yield* this.pushCount(line.length - n);\n                yield* this.pushNewline();\n                return yield* this.parseBlockScalar();\n            default:\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseFlowCollection() {\n        let nl, sp;\n        let indent = -1;\n        do {\n            nl = yield* this.pushNewline();\n            if (nl > 0) {\n                sp = yield* this.pushSpaces(false);\n                this.indentValue = indent = sp;\n            }\n            else {\n                sp = 0;\n            }\n            sp += yield* this.pushSpaces(true);\n        } while (nl + sp > 0);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('flow');\n        if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n            (indent === 0 &&\n                (line.startsWith('---') || line.startsWith('...')) &&\n                isEmpty(line[3]))) {\n            // Allowing for the terminal ] or } at the same (rather than greater)\n            // indent level as the initial [ or { is technically invalid, but\n            // failing here would be surprising to users.\n            const atFlowEndMarker = indent === this.indentNext - 1 &&\n                this.flowLevel === 1 &&\n                (line[0] === ']' || line[0] === '}');\n            if (!atFlowEndMarker) {\n                // this is an error\n                this.flowLevel = 0;\n                yield cst.FLOW_END;\n                return yield* this.parseLineStart();\n            }\n        }\n        let n = 0;\n        while (line[n] === ',') {\n            n += yield* this.pushCount(1);\n            n += yield* this.pushSpaces(true);\n            this.flowKey = false;\n        }\n        n += yield* this.pushIndicators();\n        switch (line[n]) {\n            case undefined:\n                return 'flow';\n            case '#':\n                yield* this.pushCount(line.length - n);\n                return 'flow';\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel += 1;\n                return 'flow';\n            case '}':\n            case ']':\n                yield* this.pushCount(1);\n                this.flowKey = true;\n                this.flowLevel -= 1;\n                return this.flowLevel ? 'flow' : 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'flow';\n            case '\"':\n            case \"'\":\n                this.flowKey = true;\n                return yield* this.parseQuotedScalar();\n            case ':': {\n                const next = this.charAt(1);\n                if (this.flowKey || isEmpty(next) || next === ',') {\n                    this.flowKey = false;\n                    yield* this.pushCount(1);\n                    yield* this.pushSpaces(true);\n                    return 'flow';\n                }\n            }\n            // fallthrough\n            default:\n                this.flowKey = false;\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseQuotedScalar() {\n        const quote = this.charAt(0);\n        let end = this.buffer.indexOf(quote, this.pos + 1);\n        if (quote === \"'\") {\n            while (end !== -1 && this.buffer[end + 1] === \"'\")\n                end = this.buffer.indexOf(\"'\", end + 2);\n        }\n        else {\n            // double-quote\n            while (end !== -1) {\n                let n = 0;\n                while (this.buffer[end - 1 - n] === '\\\\')\n                    n += 1;\n                if (n % 2 === 0)\n                    break;\n                end = this.buffer.indexOf('\"', end + 1);\n            }\n        }\n        // Only looking for newlines within the quotes\n        const qb = this.buffer.substring(0, end);\n        let nl = qb.indexOf('\\n', this.pos);\n        if (nl !== -1) {\n            while (nl !== -1) {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = qb.indexOf('\\n', cs);\n            }\n            if (nl !== -1) {\n                // this is an error caused by an unexpected unindent\n                end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n            }\n        }\n        if (end === -1) {\n            if (!this.atEnd)\n                return this.setNext('quoted-scalar');\n            end = this.buffer.length;\n        }\n        yield* this.pushToIndex(end + 1, false);\n        return this.flowLevel ? 'flow' : 'doc';\n    }\n    *parseBlockScalarHeader() {\n        this.blockScalarIndent = -1;\n        this.blockScalarKeep = false;\n        let i = this.pos;\n        while (true) {\n            const ch = this.buffer[++i];\n            if (ch === '+')\n                this.blockScalarKeep = true;\n            else if (ch > '0' && ch <= '9')\n                this.blockScalarIndent = Number(ch) - 1;\n            else if (ch !== '-')\n                break;\n        }\n        return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n    }\n    *parseBlockScalar() {\n        let nl = this.pos - 1; // may be -1 if this.pos === 0\n        let indent = 0;\n        let ch;\n        loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n            switch (ch) {\n                case ' ':\n                    indent += 1;\n                    break;\n                case '\\n':\n                    nl = i;\n                    indent = 0;\n                    break;\n                case '\\r': {\n                    const next = this.buffer[i + 1];\n                    if (!next && !this.atEnd)\n                        return this.setNext('block-scalar');\n                    if (next === '\\n')\n                        break;\n                } // fallthrough\n                default:\n                    break loop;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('block-scalar');\n        if (indent >= this.indentNext) {\n            if (this.blockScalarIndent === -1)\n                this.indentNext = indent;\n            else {\n                this.indentNext =\n                    this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n            }\n            do {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = this.buffer.indexOf('\\n', cs);\n            } while (nl !== -1);\n            if (nl === -1) {\n                if (!this.atEnd)\n                    return this.setNext('block-scalar');\n                nl = this.buffer.length;\n            }\n        }\n        // Trailing insufficiently indented tabs are invalid.\n        // To catch that during parsing, we include them in the block scalar value.\n        let i = nl + 1;\n        ch = this.buffer[i];\n        while (ch === ' ')\n            ch = this.buffer[++i];\n        if (ch === '\\t') {\n            while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n                ch = this.buffer[++i];\n            nl = i - 1;\n        }\n        else if (!this.blockScalarKeep) {\n            do {\n                let i = nl - 1;\n                let ch = this.buffer[i];\n                if (ch === '\\r')\n                    ch = this.buffer[--i];\n                const lastChar = i; // Drop the line if last char not more indented\n                while (ch === ' ')\n                    ch = this.buffer[--i];\n                if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n                    nl = i;\n                else\n                    break;\n            } while (true);\n        }\n        yield cst.SCALAR;\n        yield* this.pushToIndex(nl + 1, true);\n        return yield* this.parseLineStart();\n    }\n    *parsePlainScalar() {\n        const inFlow = this.flowLevel > 0;\n        let end = this.pos - 1;\n        let i = this.pos - 1;\n        let ch;\n        while ((ch = this.buffer[++i])) {\n            if (ch === ':') {\n                const next = this.buffer[i + 1];\n                if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                end = i;\n            }\n            else if (isEmpty(ch)) {\n                let next = this.buffer[i + 1];\n                if (ch === '\\r') {\n                    if (next === '\\n') {\n                        i += 1;\n                        ch = '\\n';\n                        next = this.buffer[i + 1];\n                    }\n                    else\n                        end = i;\n                }\n                if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                if (ch === '\\n') {\n                    const cs = this.continueScalar(i + 1);\n                    if (cs === -1)\n                        break;\n                    i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n                }\n            }\n            else {\n                if (inFlow && flowIndicatorChars.has(ch))\n                    break;\n                end = i;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('plain-scalar');\n        yield cst.SCALAR;\n        yield* this.pushToIndex(end + 1, true);\n        return inFlow ? 'flow' : 'doc';\n    }\n    *pushCount(n) {\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos += n;\n            return n;\n        }\n        return 0;\n    }\n    *pushToIndex(i, allowEmpty) {\n        const s = this.buffer.slice(this.pos, i);\n        if (s) {\n            yield s;\n            this.pos += s.length;\n            return s.length;\n        }\n        else if (allowEmpty)\n            yield '';\n        return 0;\n    }\n    *pushIndicators() {\n        let n = 0;\n        loop: while (true) {\n            switch (this.charAt(0)) {\n                case '!':\n                    n += yield* this.pushTag();\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '&':\n                    n += yield* this.pushUntil(isNotAnchorChar);\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '-': // this is an error\n                case '?': // this is an error outside flow collections\n                case ':': {\n                    const inFlow = this.flowLevel > 0;\n                    const ch1 = this.charAt(1);\n                    if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n                        if (!inFlow)\n                            this.indentNext = this.indentValue + 1;\n                        else if (this.flowKey)\n                            this.flowKey = false;\n                        n += yield* this.pushCount(1);\n                        n += yield* this.pushSpaces(true);\n                        continue loop;\n                    }\n                }\n            }\n            break loop;\n        }\n        return n;\n    }\n    *pushTag() {\n        if (this.charAt(1) === '<') {\n            let i = this.pos + 2;\n            let ch = this.buffer[i];\n            while (!isEmpty(ch) && ch !== '>')\n                ch = this.buffer[++i];\n            return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n        }\n        else {\n            let i = this.pos + 1;\n            let ch = this.buffer[i];\n            while (ch) {\n                if (tagChars.has(ch))\n                    ch = this.buffer[++i];\n                else if (ch === '%' &&\n                    hexDigits.has(this.buffer[i + 1]) &&\n                    hexDigits.has(this.buffer[i + 2])) {\n                    ch = this.buffer[(i += 3)];\n                }\n                else\n                    break;\n            }\n            return yield* this.pushToIndex(i, false);\n        }\n    }\n    *pushNewline() {\n        const ch = this.buffer[this.pos];\n        if (ch === '\\n')\n            return yield* this.pushCount(1);\n        else if (ch === '\\r' && this.charAt(1) === '\\n')\n            return yield* this.pushCount(2);\n        else\n            return 0;\n    }\n    *pushSpaces(allowTabs) {\n        let i = this.pos - 1;\n        let ch;\n        do {\n            ch = this.buffer[++i];\n        } while (ch === ' ' || (allowTabs && ch === '\\t'));\n        const n = i - this.pos;\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos = i;\n        }\n        return n;\n    }\n    *pushUntil(test) {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (!test(ch))\n            ch = this.buffer[++i];\n        return yield* this.pushToIndex(i, false);\n    }\n}\n\nexports.Lexer = Lexer;\n","'use strict';\n\n/**\n * Tracks newlines during parsing in order to provide an efficient API for\n * determining the one-indexed `{ line, col }` position for any offset\n * within the input.\n */\nclass LineCounter {\n    constructor() {\n        this.lineStarts = [];\n        /**\n         * Should be called in ascending order. Otherwise, call\n         * `lineCounter.lineStarts.sort()` before calling `linePos()`.\n         */\n        this.addNewLine = (offset) => this.lineStarts.push(offset);\n        /**\n         * Performs a binary search and returns the 1-indexed { line, col }\n         * position of `offset`. If `line === 0`, `addNewLine` has never been\n         * called or `offset` is before the first known newline.\n         */\n        this.linePos = (offset) => {\n            let low = 0;\n            let high = this.lineStarts.length;\n            while (low < high) {\n                const mid = (low + high) >> 1; // Math.floor((low + high) / 2)\n                if (this.lineStarts[mid] < offset)\n                    low = mid + 1;\n                else\n                    high = mid;\n            }\n            if (this.lineStarts[low] === offset)\n                return { line: low + 1, col: 1 };\n            if (low === 0)\n                return { line: 0, col: offset };\n            const start = this.lineStarts[low - 1];\n            return { line: low, col: offset - start + 1 };\n        };\n    }\n}\n\nexports.LineCounter = LineCounter;\n","'use strict';\n\nvar node_process = require('process');\nvar cst = require('./cst.js');\nvar lexer = require('./lexer.js');\n\nfunction includesToken(list, type) {\n    for (let i = 0; i < list.length; ++i)\n        if (list[i].type === type)\n            return true;\n    return false;\n}\nfunction findNonEmptyIndex(list) {\n    for (let i = 0; i < list.length; ++i) {\n        switch (list[i].type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                break;\n            default:\n                return i;\n        }\n    }\n    return -1;\n}\nfunction isFlowToken(token) {\n    switch (token?.type) {\n        case 'alias':\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'flow-collection':\n            return true;\n        default:\n            return false;\n    }\n}\nfunction getPrevProps(parent) {\n    switch (parent.type) {\n        case 'document':\n            return parent.start;\n        case 'block-map': {\n            const it = parent.items[parent.items.length - 1];\n            return it.sep ?? it.start;\n        }\n        case 'block-seq':\n            return parent.items[parent.items.length - 1].start;\n        /* istanbul ignore next should not happen */\n        default:\n            return [];\n    }\n}\n/** Note: May modify input array */\nfunction getFirstKeyStartProps(prev) {\n    if (prev.length === 0)\n        return [];\n    let i = prev.length;\n    loop: while (--i >= 0) {\n        switch (prev[i].type) {\n            case 'doc-start':\n            case 'explicit-key-ind':\n            case 'map-value-ind':\n            case 'seq-item-ind':\n            case 'newline':\n                break loop;\n        }\n    }\n    while (prev[++i]?.type === 'space') {\n        /* loop */\n    }\n    return prev.splice(i, prev.length);\n}\nfunction arrayPushArray(target, source) {\n    // May exhaust call stack with large `source` array\n    if (source.length < 1e5)\n        Array.prototype.push.apply(target, source);\n    else\n        for (let i = 0; i < source.length; ++i)\n            target.push(source[i]);\n}\nfunction fixFlowSeqItems(fc) {\n    if (fc.start.type === 'flow-seq-start') {\n        for (const it of fc.items) {\n            if (it.sep &&\n                !it.value &&\n                !includesToken(it.start, 'explicit-key-ind') &&\n                !includesToken(it.sep, 'map-value-ind')) {\n                if (it.key)\n                    it.value = it.key;\n                delete it.key;\n                if (isFlowToken(it.value)) {\n                    if (it.value.end)\n                        arrayPushArray(it.value.end, it.sep);\n                    else\n                        it.value.end = it.sep;\n                }\n                else\n                    arrayPushArray(it.start, it.sep);\n                delete it.sep;\n            }\n        }\n    }\n}\n/**\n * A YAML concrete syntax tree (CST) parser\n *\n * ```ts\n * const src: string = ...\n * for (const token of new Parser().parse(src)) {\n *   // token: Token\n * }\n * ```\n *\n * To use the parser with a user-provided lexer:\n *\n * ```ts\n * function* parse(source: string, lexer: Lexer) {\n *   const parser = new Parser()\n *   for (const lexeme of lexer.lex(source))\n *     yield* parser.next(lexeme)\n *   yield* parser.end()\n * }\n *\n * const src: string = ...\n * const lexer = new Lexer()\n * for (const token of parse(src, lexer)) {\n *   // token: Token\n * }\n * ```\n */\nclass Parser {\n    /**\n     * @param onNewLine - If defined, called separately with the start position of\n     *   each new line (in `parse()`, including the start of input).\n     */\n    constructor(onNewLine) {\n        /** If true, space and sequence indicators count as indentation */\n        this.atNewLine = true;\n        /** If true, next token is a scalar value */\n        this.atScalar = false;\n        /** Current indentation level */\n        this.indent = 0;\n        /** Current offset since the start of parsing */\n        this.offset = 0;\n        /** On the same line with a block map key */\n        this.onKeyLine = false;\n        /** Top indicates the node that's currently being built */\n        this.stack = [];\n        /** The source of the current token, set in parse() */\n        this.source = '';\n        /** The type of the current token, set in parse() */\n        this.type = '';\n        // Must be defined after `next()`\n        this.lexer = new lexer.Lexer();\n        this.onNewLine = onNewLine;\n    }\n    /**\n     * Parse `source` as a YAML stream.\n     * If `incomplete`, a part of the last line may be left as a buffer for the next call.\n     *\n     * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.\n     *\n     * @returns A generator of tokens representing each directive, document, and other structure.\n     */\n    *parse(source, incomplete = false) {\n        if (this.onNewLine && this.offset === 0)\n            this.onNewLine(0);\n        for (const lexeme of this.lexer.lex(source, incomplete))\n            yield* this.next(lexeme);\n        if (!incomplete)\n            yield* this.end();\n    }\n    /**\n     * Advance the parser by the `source` of one lexical token.\n     */\n    *next(source) {\n        this.source = source;\n        if (node_process.env.LOG_TOKENS)\n            console.log('|', cst.prettyToken(source));\n        if (this.atScalar) {\n            this.atScalar = false;\n            yield* this.step();\n            this.offset += source.length;\n            return;\n        }\n        const type = cst.tokenType(source);\n        if (!type) {\n            const message = `Not a YAML token: ${source}`;\n            yield* this.pop({ type: 'error', offset: this.offset, message, source });\n            this.offset += source.length;\n        }\n        else if (type === 'scalar') {\n            this.atNewLine = false;\n            this.atScalar = true;\n            this.type = 'scalar';\n        }\n        else {\n            this.type = type;\n            yield* this.step();\n            switch (type) {\n                case 'newline':\n                    this.atNewLine = true;\n                    this.indent = 0;\n                    if (this.onNewLine)\n                        this.onNewLine(this.offset + source.length);\n                    break;\n                case 'space':\n                    if (this.atNewLine && source[0] === ' ')\n                        this.indent += source.length;\n                    break;\n                case 'explicit-key-ind':\n                case 'map-value-ind':\n                case 'seq-item-ind':\n                    if (this.atNewLine)\n                        this.indent += source.length;\n                    break;\n                case 'doc-mode':\n                case 'flow-error-end':\n                    return;\n                default:\n                    this.atNewLine = false;\n            }\n            this.offset += source.length;\n        }\n    }\n    /** Call at end of input to push out any remaining constructions */\n    *end() {\n        while (this.stack.length > 0)\n            yield* this.pop();\n    }\n    get sourceToken() {\n        const st = {\n            type: this.type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n        return st;\n    }\n    *step() {\n        const top = this.peek(1);\n        if (this.type === 'doc-end' && top?.type !== 'doc-end') {\n            while (this.stack.length > 0)\n                yield* this.pop();\n            this.stack.push({\n                type: 'doc-end',\n                offset: this.offset,\n                source: this.source\n            });\n            return;\n        }\n        if (!top)\n            return yield* this.stream();\n        switch (top.type) {\n            case 'document':\n                return yield* this.document(top);\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return yield* this.scalar(top);\n            case 'block-scalar':\n                return yield* this.blockScalar(top);\n            case 'block-map':\n                return yield* this.blockMap(top);\n            case 'block-seq':\n                return yield* this.blockSequence(top);\n            case 'flow-collection':\n                return yield* this.flowCollection(top);\n            case 'doc-end':\n                return yield* this.documentEnd(top);\n        }\n        /* istanbul ignore next should not happen */\n        yield* this.pop();\n    }\n    peek(n) {\n        return this.stack[this.stack.length - n];\n    }\n    *pop(error) {\n        const token = error ?? this.stack.pop();\n        /* istanbul ignore if should not happen */\n        if (!token) {\n            const message = 'Tried to pop an empty stack';\n            yield { type: 'error', offset: this.offset, source: '', message };\n        }\n        else if (this.stack.length === 0) {\n            yield token;\n        }\n        else {\n            const top = this.peek(1);\n            if (token.type === 'block-scalar') {\n                // Block scalars use their parent rather than header indent\n                token.indent = 'indent' in top ? top.indent : 0;\n            }\n            else if (token.type === 'flow-collection' && top.type === 'document') {\n                // Ignore all indent for top-level flow collections\n                token.indent = 0;\n            }\n            if (token.type === 'flow-collection')\n                fixFlowSeqItems(token);\n            switch (top.type) {\n                case 'document':\n                    top.value = token;\n                    break;\n                case 'block-scalar':\n                    top.props.push(token); // error\n                    break;\n                case 'block-map': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value) {\n                        top.items.push({ start: [], key: token, sep: [] });\n                        this.onKeyLine = true;\n                        return;\n                    }\n                    else if (it.sep) {\n                        it.value = token;\n                    }\n                    else {\n                        Object.assign(it, { key: token, sep: [] });\n                        this.onKeyLine = !it.explicitKey;\n                        return;\n                    }\n                    break;\n                }\n                case 'block-seq': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value)\n                        top.items.push({ start: [], value: token });\n                    else\n                        it.value = token;\n                    break;\n                }\n                case 'flow-collection': {\n                    const it = top.items[top.items.length - 1];\n                    if (!it || it.value)\n                        top.items.push({ start: [], key: token, sep: [] });\n                    else if (it.sep)\n                        it.value = token;\n                    else\n                        Object.assign(it, { key: token, sep: [] });\n                    return;\n                }\n                /* istanbul ignore next should not happen */\n                default:\n                    yield* this.pop();\n                    yield* this.pop(token);\n            }\n            if ((top.type === 'document' ||\n                top.type === 'block-map' ||\n                top.type === 'block-seq') &&\n                (token.type === 'block-map' || token.type === 'block-seq')) {\n                const last = token.items[token.items.length - 1];\n                if (last &&\n                    !last.sep &&\n                    !last.value &&\n                    last.start.length > 0 &&\n                    findNonEmptyIndex(last.start) === -1 &&\n                    (token.indent === 0 ||\n                        last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {\n                    if (top.type === 'document')\n                        top.end = last.start;\n                    else\n                        top.items.push({ start: last.start });\n                    token.items.splice(-1, 1);\n                }\n            }\n        }\n    }\n    *stream() {\n        switch (this.type) {\n            case 'directive-line':\n                yield { type: 'directive', offset: this.offset, source: this.source };\n                return;\n            case 'byte-order-mark':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                yield this.sourceToken;\n                return;\n            case 'doc-mode':\n            case 'doc-start': {\n                const doc = {\n                    type: 'document',\n                    offset: this.offset,\n                    start: []\n                };\n                if (this.type === 'doc-start')\n                    doc.start.push(this.sourceToken);\n                this.stack.push(doc);\n                return;\n            }\n        }\n        yield {\n            type: 'error',\n            offset: this.offset,\n            message: `Unexpected ${this.type} token in YAML stream`,\n            source: this.source\n        };\n    }\n    *document(doc) {\n        if (doc.value)\n            return yield* this.lineEnd(doc);\n        switch (this.type) {\n            case 'doc-start': {\n                if (findNonEmptyIndex(doc.start) !== -1) {\n                    yield* this.pop();\n                    yield* this.step();\n                }\n                else\n                    doc.start.push(this.sourceToken);\n                return;\n            }\n            case 'anchor':\n            case 'tag':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                doc.start.push(this.sourceToken);\n                return;\n        }\n        const bv = this.startBlockValue(doc);\n        if (bv)\n            this.stack.push(bv);\n        else {\n            yield {\n                type: 'error',\n                offset: this.offset,\n                message: `Unexpected ${this.type} token in YAML document`,\n                source: this.source\n            };\n        }\n    }\n    *scalar(scalar) {\n        if (this.type === 'map-value-ind') {\n            const prev = getPrevProps(this.peek(2));\n            const start = getFirstKeyStartProps(prev);\n            let sep;\n            if (scalar.end) {\n                sep = scalar.end;\n                sep.push(this.sourceToken);\n                delete scalar.end;\n            }\n            else\n                sep = [this.sourceToken];\n            const map = {\n                type: 'block-map',\n                offset: scalar.offset,\n                indent: scalar.indent,\n                items: [{ start, key: scalar, sep }]\n            };\n            this.onKeyLine = true;\n            this.stack[this.stack.length - 1] = map;\n        }\n        else\n            yield* this.lineEnd(scalar);\n    }\n    *blockScalar(scalar) {\n        switch (this.type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                scalar.props.push(this.sourceToken);\n                return;\n            case 'scalar':\n                scalar.source = this.source;\n                // block-scalar source includes trailing newline\n                this.atNewLine = true;\n                this.indent = 0;\n                if (this.onNewLine) {\n                    let nl = this.source.indexOf('\\n') + 1;\n                    while (nl !== 0) {\n                        this.onNewLine(this.offset + nl);\n                        nl = this.source.indexOf('\\n', nl) + 1;\n                    }\n                }\n                yield* this.pop();\n                break;\n            /* istanbul ignore next should not happen */\n            default:\n                yield* this.pop();\n                yield* this.step();\n        }\n    }\n    *blockMap(map) {\n        const it = map.items[map.items.length - 1];\n        // it.sep is true-ish if pair already has key or : separator\n        switch (this.type) {\n            case 'newline':\n                this.onKeyLine = false;\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value) {\n                    map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    if (this.atIndentedComment(it.start, map.indent)) {\n                        const prev = map.items[map.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            map.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n        }\n        if (this.indent >= map.indent) {\n            const atMapIndent = !this.onKeyLine && this.indent === map.indent;\n            const atNextItem = atMapIndent &&\n                (it.sep || it.explicitKey) &&\n                this.type !== 'seq-item-ind';\n            // For empty nodes, assign newline-separated not indented empty tokens to following node\n            let start = [];\n            if (atNextItem && it.sep && !it.value) {\n                const nl = [];\n                for (let i = 0; i < it.sep.length; ++i) {\n                    const st = it.sep[i];\n                    switch (st.type) {\n                        case 'newline':\n                            nl.push(i);\n                            break;\n                        case 'space':\n                            break;\n                        case 'comment':\n                            if (st.indent > map.indent)\n                                nl.length = 0;\n                            break;\n                        default:\n                            nl.length = 0;\n                    }\n                }\n                if (nl.length >= 2)\n                    start = it.sep.splice(nl[1]);\n            }\n            switch (this.type) {\n                case 'anchor':\n                case 'tag':\n                    if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        it.sep.push(this.sourceToken);\n                    }\n                    else {\n                        it.start.push(this.sourceToken);\n                    }\n                    return;\n                case 'explicit-key-ind':\n                    if (!it.sep && !it.explicitKey) {\n                        it.start.push(this.sourceToken);\n                        it.explicitKey = true;\n                    }\n                    else if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start, explicitKey: true });\n                    }\n                    else {\n                        this.stack.push({\n                            type: 'block-map',\n                            offset: this.offset,\n                            indent: this.indent,\n                            items: [{ start: [this.sourceToken], explicitKey: true }]\n                        });\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'map-value-ind':\n                    if (it.explicitKey) {\n                        if (!it.sep) {\n                            if (includesToken(it.start, 'newline')) {\n                                Object.assign(it, { key: null, sep: [this.sourceToken] });\n                            }\n                            else {\n                                const start = getFirstKeyStartProps(it.start);\n                                this.stack.push({\n                                    type: 'block-map',\n                                    offset: this.offset,\n                                    indent: this.indent,\n                                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                                });\n                            }\n                        }\n                        else if (it.value) {\n                            map.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else if (isFlowToken(it.key) &&\n                            !includesToken(it.sep, 'newline')) {\n                            const start = getFirstKeyStartProps(it.start);\n                            const key = it.key;\n                            const sep = it.sep;\n                            sep.push(this.sourceToken);\n                            // @ts-expect-error type guard is wrong here\n                            delete it.key;\n                            // @ts-expect-error type guard is wrong here\n                            delete it.sep;\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key, sep }]\n                            });\n                        }\n                        else if (start.length > 0) {\n                            // Not actually at next item\n                            it.sep = it.sep.concat(start, this.sourceToken);\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    else {\n                        if (!it.sep) {\n                            Object.assign(it, { key: null, sep: [this.sourceToken] });\n                        }\n                        else if (it.value || atNextItem) {\n                            map.items.push({ start, key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start: [], key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (atNextItem || it.value) {\n                        map.items.push({ start, key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        this.stack.push(fs);\n                    }\n                    else {\n                        Object.assign(it, { key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    return;\n                }\n                default: {\n                    const bv = this.startBlockValue(map);\n                    if (bv) {\n                        if (bv.type === 'block-seq') {\n                            if (!it.explicitKey &&\n                                it.sep &&\n                                !includesToken(it.sep, 'newline')) {\n                                yield* this.pop({\n                                    type: 'error',\n                                    offset: this.offset,\n                                    message: 'Unexpected block-seq-ind on same line with key',\n                                    source: this.source\n                                });\n                                return;\n                            }\n                        }\n                        else if (atMapIndent) {\n                            map.items.push({ start });\n                        }\n                        this.stack.push(bv);\n                        return;\n                    }\n                }\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *blockSequence(seq) {\n        const it = seq.items[seq.items.length - 1];\n        switch (this.type) {\n            case 'newline':\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        seq.items.push({ start: [this.sourceToken] });\n                }\n                else\n                    it.start.push(this.sourceToken);\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value)\n                    seq.items.push({ start: [this.sourceToken] });\n                else {\n                    if (this.atIndentedComment(it.start, seq.indent)) {\n                        const prev = seq.items[seq.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            seq.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'anchor':\n            case 'tag':\n                if (it.value || this.indent <= seq.indent)\n                    break;\n                it.start.push(this.sourceToken);\n                return;\n            case 'seq-item-ind':\n                if (this.indent !== seq.indent)\n                    break;\n                if (it.value || includesToken(it.start, 'seq-item-ind'))\n                    seq.items.push({ start: [this.sourceToken] });\n                else\n                    it.start.push(this.sourceToken);\n                return;\n        }\n        if (this.indent > seq.indent) {\n            const bv = this.startBlockValue(seq);\n            if (bv) {\n                this.stack.push(bv);\n                return;\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *flowCollection(fc) {\n        const it = fc.items[fc.items.length - 1];\n        if (this.type === 'flow-error-end') {\n            let top;\n            do {\n                yield* this.pop();\n                top = this.peek(1);\n            } while (top?.type === 'flow-collection');\n        }\n        else if (fc.end.length === 0) {\n            switch (this.type) {\n                case 'comma':\n                case 'explicit-key-ind':\n                    if (!it || it.sep)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'map-value-ind':\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        Object.assign(it, { key: null, sep: [this.sourceToken] });\n                    return;\n                case 'space':\n                case 'comment':\n                case 'newline':\n                case 'anchor':\n                case 'tag':\n                    if (!it || it.value)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: fs, sep: [] });\n                    else if (it.sep)\n                        this.stack.push(fs);\n                    else\n                        Object.assign(it, { key: fs, sep: [] });\n                    return;\n                }\n                case 'flow-map-end':\n                case 'flow-seq-end':\n                    fc.end.push(this.sourceToken);\n                    return;\n            }\n            const bv = this.startBlockValue(fc);\n            /* istanbul ignore else should not happen */\n            if (bv)\n                this.stack.push(bv);\n            else {\n                yield* this.pop();\n                yield* this.step();\n            }\n        }\n        else {\n            const parent = this.peek(2);\n            if (parent.type === 'block-map' &&\n                ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||\n                    (this.type === 'newline' &&\n                        !parent.items[parent.items.length - 1].sep))) {\n                yield* this.pop();\n                yield* this.step();\n            }\n            else if (this.type === 'map-value-ind' &&\n                parent.type !== 'flow-collection') {\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                fixFlowSeqItems(fc);\n                const sep = fc.end.splice(1, fc.end.length);\n                sep.push(this.sourceToken);\n                const map = {\n                    type: 'block-map',\n                    offset: fc.offset,\n                    indent: fc.indent,\n                    items: [{ start, key: fc, sep }]\n                };\n                this.onKeyLine = true;\n                this.stack[this.stack.length - 1] = map;\n            }\n            else {\n                yield* this.lineEnd(fc);\n            }\n        }\n    }\n    flowScalar(type) {\n        if (this.onNewLine) {\n            let nl = this.source.indexOf('\\n') + 1;\n            while (nl !== 0) {\n                this.onNewLine(this.offset + nl);\n                nl = this.source.indexOf('\\n', nl) + 1;\n            }\n        }\n        return {\n            type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n    }\n    startBlockValue(parent) {\n        switch (this.type) {\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return this.flowScalar(this.type);\n            case 'block-scalar-header':\n                return {\n                    type: 'block-scalar',\n                    offset: this.offset,\n                    indent: this.indent,\n                    props: [this.sourceToken],\n                    source: ''\n                };\n            case 'flow-map-start':\n            case 'flow-seq-start':\n                return {\n                    type: 'flow-collection',\n                    offset: this.offset,\n                    indent: this.indent,\n                    start: this.sourceToken,\n                    items: [],\n                    end: []\n                };\n            case 'seq-item-ind':\n                return {\n                    type: 'block-seq',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start: [this.sourceToken] }]\n                };\n            case 'explicit-key-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                start.push(this.sourceToken);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, explicitKey: true }]\n                };\n            }\n            case 'map-value-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                };\n            }\n        }\n        return null;\n    }\n    atIndentedComment(start, indent) {\n        if (this.type !== 'comment')\n            return false;\n        if (this.indent <= indent)\n            return false;\n        return start.every(st => st.type === 'newline' || st.type === 'space');\n    }\n    *documentEnd(docEnd) {\n        if (this.type !== 'doc-mode') {\n            if (docEnd.end)\n                docEnd.end.push(this.sourceToken);\n            else\n                docEnd.end = [this.sourceToken];\n            if (this.type === 'newline')\n                yield* this.pop();\n        }\n    }\n    *lineEnd(token) {\n        switch (this.type) {\n            case 'comma':\n            case 'doc-start':\n            case 'doc-end':\n            case 'flow-seq-end':\n            case 'flow-map-end':\n            case 'map-value-ind':\n                yield* this.pop();\n                yield* this.step();\n                break;\n            case 'newline':\n                this.onKeyLine = false;\n            // fallthrough\n            case 'space':\n            case 'comment':\n            default:\n                // all other values are errors\n                if (token.end)\n                    token.end.push(this.sourceToken);\n                else\n                    token.end = [this.sourceToken];\n                if (this.type === 'newline')\n                    yield* this.pop();\n        }\n    }\n}\n\nexports.Parser = Parser;\n","'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar errors = require('./errors.js');\nvar log = require('./log.js');\nvar identity = require('./nodes/identity.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\n\nfunction parseOptions(options) {\n    const prettyErrors = options.prettyErrors !== false;\n    const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;\n    return { lineCounter: lineCounter$1, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n *   EmptyStream and contain additional stream information. In\n *   TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n    const composer$1 = new composer.Composer(options);\n    const docs = Array.from(composer$1.compose(parser$1.parse(source)));\n    if (prettyErrors && lineCounter)\n        for (const doc of docs) {\n            doc.errors.forEach(errors.prettifyError(source, lineCounter));\n            doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n        }\n    if (docs.length > 0)\n        return docs;\n    return Object.assign([], { empty: true }, composer$1.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n    const composer$1 = new composer.Composer(options);\n    // `doc` is always set by compose.end(true) at the very latest\n    let doc = null;\n    for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {\n        if (!doc)\n            doc = _doc;\n        else if (doc.options.logLevel !== 'silent') {\n            doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n            break;\n        }\n    }\n    if (prettyErrors && lineCounter) {\n        doc.errors.forEach(errors.prettifyError(source, lineCounter));\n        doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n    }\n    return doc;\n}\nfunction parse(src, reviver, options) {\n    let _reviver = undefined;\n    if (typeof reviver === 'function') {\n        _reviver = reviver;\n    }\n    else if (options === undefined && reviver && typeof reviver === 'object') {\n        options = reviver;\n    }\n    const doc = parseDocument(src, options);\n    if (!doc)\n        return null;\n    doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));\n    if (doc.errors.length > 0) {\n        if (doc.options.logLevel !== 'silent')\n            throw doc.errors[0];\n        else\n            doc.errors = [];\n    }\n    return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n    let _replacer = null;\n    if (typeof replacer === 'function' || Array.isArray(replacer)) {\n        _replacer = replacer;\n    }\n    else if (options === undefined && replacer) {\n        options = replacer;\n    }\n    if (typeof options === 'string')\n        options = options.length;\n    if (typeof options === 'number') {\n        const indent = Math.round(options);\n        options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n    }\n    if (value === undefined) {\n        const { keepUndefined } = options ?? replacer ?? {};\n        if (!keepUndefined)\n            return undefined;\n    }\n    if (identity.isDocument(value) && !_replacer)\n        return value.toString(options);\n    return new Document.Document(value, _replacer, options).toString(options);\n}\n\nexports.parse = parse;\nexports.parseAllDocuments = parseAllDocuments;\nexports.parseDocument = parseDocument;\nexports.stringify = stringify;\n","'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar Schema = require('./schema/Schema.js');\nvar errors = require('./errors.js');\nvar Alias = require('./nodes/Alias.js');\nvar identity = require('./nodes/identity.js');\nvar Pair = require('./nodes/Pair.js');\nvar Scalar = require('./nodes/Scalar.js');\nvar YAMLMap = require('./nodes/YAMLMap.js');\nvar YAMLSeq = require('./nodes/YAMLSeq.js');\nvar cst = require('./parse/cst.js');\nvar lexer = require('./parse/lexer.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\nvar publicApi = require('./public-api.js');\nvar visit = require('./visit.js');\n\n\n\nexports.Composer = composer.Composer;\nexports.Document = Document.Document;\nexports.Schema = Schema.Schema;\nexports.YAMLError = errors.YAMLError;\nexports.YAMLParseError = errors.YAMLParseError;\nexports.YAMLWarning = errors.YAMLWarning;\nexports.Alias = Alias.Alias;\nexports.isAlias = identity.isAlias;\nexports.isCollection = identity.isCollection;\nexports.isDocument = identity.isDocument;\nexports.isMap = identity.isMap;\nexports.isNode = identity.isNode;\nexports.isPair = identity.isPair;\nexports.isScalar = identity.isScalar;\nexports.isSeq = identity.isSeq;\nexports.Pair = Pair.Pair;\nexports.Scalar = Scalar.Scalar;\nexports.YAMLMap = YAMLMap.YAMLMap;\nexports.YAMLSeq = YAMLSeq.YAMLSeq;\nexports.CST = cst;\nexports.Lexer = lexer.Lexer;\nexports.LineCounter = lineCounter.LineCounter;\nexports.Parser = parser.Parser;\nexports.parse = publicApi.parse;\nexports.parseAllDocuments = publicApi.parseAllDocuments;\nexports.parseDocument = publicApi.parseDocument;\nexports.stringify = publicApi.stringify;\nexports.visit = visit.visit;\nexports.visitAsync = visit.visitAsync;\n","import { b as listCredentialAssignmentsByTarget$1, g as selectCredentialInstancesForScope$2, h as selectCredentialInstanceById$2, m as listCredentialInstancesForAssignment } from \"./store-4At2Wnk9.mjs\";\nimport { CREDENTIAL_SCOPE_TYPES, buildConnectDeeplink, graphqlIntrospectionToAppTemplate, inferGraphqlAuthFromProbe, isRecord, mcpEntityId, mcpProbeToAppTemplate, normalizeCredentialList, openApiSpecToAppTemplate } from \"@keystrokehq/shared\";\nimport { decryptCredentialPayload, encryptCredentialPayload, ensureOAuthCredentialInstance, getBoundProjectScopeId, getServerTenantScopeId, isDatabaseInitialized, selectCredentialInstanceById } from \"@keystrokehq/database\";\nimport { ensureOAuthApp, getDecryptedOAuthAppById, getDecryptedOAuthConnectionById, resolveOAuthAccessToken, saveOAuthConnection, selectOrganizationById, selectProjectById } from \"@keystrokehq/platform-database\";\nimport { readCredentialInstanceSecret } from \"@keystrokehq/secrets\";\nimport { selectCredentialInstanceById as selectCredentialInstanceById$1, selectCredentialInstancesForScope as selectCredentialInstancesForScope$1, touchCredentialInstanceLastUsed as touchCredentialInstanceLastUsed$1 } from \"@keystrokehq/credentials/store\";\nimport { jsonSchema, tool } from \"ai\";\nimport { PublicHttpUrlError, connectMcpDefinition, createToolName, defineMcp as defineMcp$1, discoverOAuthServerInfo, exchangeAuthorization, mergeOAuthScopes, normalizeInputSchema, probeMcpAuth, probeMcpServerInfo, registerClient, startAuthorization } from \"@keystrokehq/mcp\";\nimport YAML from \"yaml\";\n//#region src/format-error.ts\nfunction formatCredentialErrorMessage(error, connect) {\n\tswitch (error.code) {\n\t\tcase \"missing_credentials\":\n\t\t\tif (connect) {\n\t\t\t\tconst connectUrl = buildConnectDeeplink({\n\t\t\t\t\twebUrl: connect.webUrl,\n\t\t\t\t\torgSlug: connect.orgSlug,\n\t\t\t\t\tappSlug: error.key\n\t\t\t\t});\n\t\t\t\treturn `This agent needs the \\`${error.key}\\` credential. Connect it here: ${connectUrl}`;\n\t\t\t}\n\t\t\treturn `This agent needs the \\`${error.key}\\` credential. Run \\`keystroke connect ${error.key}\\` or \\`keystroke credentials set ${error.key}\\` to configure it.`;\n\t\tcase \"needs_selection\":\n\t\t\tif (connect) {\n\t\t\t\tconst connectUrl = buildConnectDeeplink({\n\t\t\t\t\twebUrl: connect.webUrl,\n\t\t\t\t\torgSlug: connect.orgSlug,\n\t\t\t\t\tappSlug: error.key\n\t\t\t\t});\n\t\t\t\treturn `Multiple \\`${error.key}\\` credentials are available. Pick one here: ${connectUrl}`;\n\t\t\t}\n\t\t\treturn `Multiple \\`${error.key}\\` credentials are available. Pick one in the Keystroke dashboard before running this agent.`;\n\t\tcase \"oauth_not_configured\": return error.message;\n\t}\n}\n//#endregion\n//#region src/errors.ts\nvar MissingCredentialsError = class extends Error {\n\tcode = \"missing_credentials\";\n\tkey;\n\tchainAttempted;\n\tconsumer;\n\tconstructor(options) {\n\t\tsuper(`Missing credential \"${options.key}\"`);\n\t\tthis.name = \"MissingCredentialsError\";\n\t\tthis.key = options.key;\n\t\tthis.chainAttempted = options.chainAttempted;\n\t\tthis.consumer = options.consumer;\n\t}\n};\nvar NeedsSelectionError = class extends Error {\n\tcode = \"needs_selection\";\n\tkey;\n\toptions;\n\tconsumer;\n\tconstructor(options) {\n\t\tsuper(`Credential selection required for \"${options.key}\"`);\n\t\tthis.name = \"NeedsSelectionError\";\n\t\tthis.key = options.key;\n\t\tthis.options = options.options;\n\t\tthis.consumer = options.consumer;\n\t}\n};\nvar OAuthNotConfiguredError = class extends Error {\n\tcode = \"oauth_not_configured\";\n\tconstructor(message = \"OAuth token adapter is not configured\") {\n\t\tsuper(message);\n\t\tthis.name = \"OAuthNotConfiguredError\";\n\t}\n};\nvar CredentialAccessDeniedError = class extends Error {\n\tcode = \"credential_access_denied\";\n\tinstanceId;\n\tconstructor(instanceId) {\n\t\tsuper(`Credential instance \"${instanceId}\" is not accessible in this run context`);\n\t\tthis.name = \"CredentialAccessDeniedError\";\n\t\tthis.instanceId = instanceId;\n\t}\n};\nfunction isCredentialError(error) {\n\treturn error instanceof MissingCredentialsError || error instanceof NeedsSelectionError || error instanceof OAuthNotConfiguredError;\n}\nfunction credentialScopeMatchesContext(scopeType, scopeId, context) {\n\tswitch (scopeType) {\n\t\tcase \"organization\": return scopeId === context.orgId;\n\t\tcase \"project\": return scopeId === context.projectId;\n\t\tcase \"user\": return scopeId === context.userId;\n\t}\n}\n//#endregion\n//#region src/backend/local.ts\nfunction createLocalCredentialBackend(options = {}) {\n\tconst { tokenRefresh } = options;\n\treturn {\n\t\tasync resolveApiKey(instanceId, schema) {\n\t\t\tconst row = await selectCredentialInstanceById(instanceId);\n\t\t\tif (!row) throw new MissingCredentialsError({\n\t\t\t\tkey: instanceId,\n\t\t\t\tchainAttempted: [\"api_key\"]\n\t\t\t});\n\t\t\tif (row.ciphertext) {\n\t\t\t\tconst plaintext = decryptCredentialPayload(row.ciphertext);\n\t\t\t\treturn schema.parse(JSON.parse(plaintext));\n\t\t\t}\n\t\t\tconst secret = await readCredentialInstanceSecret(instanceId);\n\t\t\tif (secret) return schema.parse(JSON.parse(secret));\n\t\t\tthrow new MissingCredentialsError({\n\t\t\t\tkey: row.appSlug,\n\t\t\t\tchainAttempted: [\"api_key\"]\n\t\t\t});\n\t\t},\n\t\tasync getOAuthAccessToken(connectionId) {\n\t\t\tconst connection = await getDecryptedOAuthConnectionById(connectionId);\n\t\t\tif (!connection) throw new Error(`OAuth connection not found: ${connectionId}`);\n\t\t\tconst app = await getDecryptedOAuthAppById(connection.appId);\n\t\t\tif (!app) throw new Error(`OAuth app not found for connection: ${connectionId}`);\n\t\t\treturn { accessToken: await resolveOAuthAccessToken(connection, app, tokenRefresh) };\n\t\t}\n\t};\n}\n//#endregion\n//#region src/backend/platform.ts\nfunction materializeUrl(baseUrl, projectId) {\n\treturn `${baseUrl}/internal/projects/${encodeURIComponent(projectId)}/credentials/materialize`;\n}\nfunction requireProjectScopeId() {\n\tconst projectId = getBoundProjectScopeId();\n\tif (!projectId) throw new Error(\"Credential backend requires project scope\");\n\treturn projectId;\n}\nfunction createPlatformCredentialBackend(options) {\n\tconst baseUrl = options.platformUrl.replace(/\\/+$/, \"\");\n\tasync function materialize(body) {\n\t\tconst response = await fetch(materializeUrl(baseUrl, requireProjectScopeId()), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${options.workerToken}`,\n\t\t\t\t\"Content-Type\": \"application/json\"\n\t\t\t},\n\t\t\tbody: JSON.stringify(body)\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tconst payload = await response.json().catch(() => null);\n\t\t\tthrow new Error(payload?.message ?? `Platform credential materialize failed (${response.status})`);\n\t\t}\n\t\tconst payload = await response.json();\n\t\tif (payload.kind === \"api_key\") return { value: payload.value };\n\t\treturn { accessToken: payload.accessToken };\n\t}\n\treturn {\n\t\tasync resolveApiKey(instanceId, schema) {\n\t\t\tconst { value } = await materialize({\n\t\t\t\tkind: \"api_key\",\n\t\t\t\tinstanceId\n\t\t\t});\n\t\t\treturn schema.parse(value);\n\t\t},\n\t\tasync getOAuthAccessToken(connectionId) {\n\t\t\tconst { accessToken } = await materialize({\n\t\t\t\tkind: \"oauth\",\n\t\t\t\tconnectionId\n\t\t\t});\n\t\t\tif (!accessToken) throw new Error(`Platform did not return an access token for connection: ${connectionId}`);\n\t\t\treturn { accessToken };\n\t\t}\n\t};\n}\n//#endregion\n//#region src/backend/create-backend.ts\n/**\n* A hosted worker is identified by the platform connection it must route through:\n* `PLATFORM_URL` + `WORKER_INTERNAL_TOKEN`. Workers never hold the decryption key, so\n* they always materialize secrets over the platform internal API; everything else\n* (platform process, standalone CLI) resolves locally against its own database.\n*\n* Org workers share one platform backend; project id comes from async job scope at\n* resolve time, not from env.\n*/\nfunction isWorkerRuntime(env = process.env) {\n\treturn Boolean(env.WORKER_INTERNAL_TOKEN?.trim() && env.PLATFORM_URL?.trim());\n}\nfunction createCredentialBackend(options = {}) {\n\tif (isWorkerRuntime()) return createPlatformCredentialBackend({\n\t\tplatformUrl: process.env.PLATFORM_URL.trim(),\n\t\tworkerToken: process.env.WORKER_INTERNAL_TOKEN.trim()\n\t});\n\treturn createLocalCredentialBackend(options);\n}\n//#endregion\n//#region src/resolve-agent-connect-context.ts\n/**\n* Web connect context (org slug + web URL) for the current project scope, or\n* `null` when unavailable — standalone, no bound project scope, or no\n* `PUBLIC_WEB_URL`. Org slug comes from the platform internal API on workers\n* (no decryption key, so no direct DB), otherwise the platform DB.\n*/\nasync function resolveAgentConnectContext() {\n\tconst projectId = getBoundProjectScopeId();\n\tif (!projectId) return null;\n\tconst webUrl = process.env.PUBLIC_WEB_URL?.trim();\n\tif (!webUrl) return null;\n\tconst orgSlug = await resolveOrgSlug(projectId);\n\tif (!orgSlug) return null;\n\treturn {\n\t\torgSlug,\n\t\twebUrl\n\t};\n}\nasync function resolveOrgSlug(projectId) {\n\tif (isWorkerRuntime()) return fetchOrgSlugFromPlatform(projectId);\n\tconst project = await selectProjectById(projectId);\n\tif (!project) return null;\n\treturn (await selectOrganizationById(project.organizationId))?.slug.trim() || null;\n}\nasync function fetchOrgSlugFromPlatform(projectId) {\n\tconst platformUrl = process.env.PLATFORM_URL?.trim();\n\tconst workerToken = process.env.WORKER_INTERNAL_TOKEN?.trim();\n\tif (!platformUrl || !workerToken) return null;\n\tconst baseUrl = platformUrl.replace(/\\/+$/, \"\");\n\tconst response = await fetch(`${baseUrl}/internal/projects/${encodeURIComponent(projectId)}/connect-context`, { headers: { Authorization: `Bearer ${workerToken}` } });\n\tif (!response.ok) return null;\n\treturn (await response.json()).orgSlug?.trim() || null;\n}\n//#endregion\n//#region src/enrich-credential-error.ts\n/** Rewrite a credential error message with a web connect deeplink when context is available. */\nasync function enrichCredentialError(error) {\n\ttry {\n\t\terror.message = formatCredentialErrorMessage(error, await resolveAgentConnectContext() ?? void 0);\n\t} catch {}\n}\n//#endregion\n//#region src/capture-credential-tool-errors.ts\n/**\n* Wrap tool `execute`s so a thrown credential error is captured (and enriched\n* with a connect deeplink) before propagating. Covers both keystroke\n* {@link AgentTool}s and native AI SDK MCP tools — MCP tools resolve credentials\n* lazily inside their own `execute`, so they need the same wrapper to surface\n* missing-credential failures for workflow retry.\n*/\nfunction captureCredentialToolErrors(tools, toolSet = {}) {\n\tlet captured;\n\tconst onError = async (error) => {\n\t\tif (isCredentialError(error)) {\n\t\t\tcaptured = error;\n\t\t\tawait enrichCredentialError(error);\n\t\t}\n\t};\n\tconst wrapped = tools.map((tool) => {\n\t\tif (!tool.execute) return tool;\n\t\tconst execute = tool.execute.bind(tool);\n\t\treturn {\n\t\t\t...tool,\n\t\t\tasync execute(...args) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await execute(...args);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait onError(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t});\n\tconst wrappedToolSet = {};\n\tfor (const [name, mcpTool] of Object.entries(toolSet)) {\n\t\tconst execute = mcpTool.execute;\n\t\tif (!execute) {\n\t\t\twrappedToolSet[name] = mcpTool;\n\t\t\tcontinue;\n\t\t}\n\t\twrappedToolSet[name] = {\n\t\t\t...mcpTool,\n\t\t\texecute: async (input, options) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await execute(input, options);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait onError(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\treturn {\n\t\ttools: wrapped,\n\t\ttoolSet: wrappedToolSet,\n\t\ttakeCredentialError: () => {\n\t\t\tconst error = captured;\n\t\t\tcaptured = void 0;\n\t\t\treturn error;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/assignments.ts\nconst EMPTY_ASSIGNMENT_SET = {\n\tbyConsumer: {},\n\twildcard: {}\n};\nfunction selectAssignedInstanceId(assignments, consumerId, credentialSlug) {\n\tif (!assignments) return;\n\tif (consumerId) {\n\t\tconst specific = assignments.byConsumer[consumerId]?.[credentialSlug];\n\t\tif (specific) return specific;\n\t}\n\treturn assignments.wildcard[credentialSlug];\n}\nfunction buildAssignmentSet(rows) {\n\tconst byConsumer = {};\n\tconst wildcard = {};\n\tfor (const row of rows) {\n\t\tif (row.consumerId === \"*\") {\n\t\t\twildcard[row.credentialSlug] = row.instanceId;\n\t\t\tcontinue;\n\t\t}\n\t\tconst bucket = byConsumer[row.consumerId] ?? {};\n\t\tbucket[row.credentialSlug] = row.instanceId;\n\t\tbyConsumer[row.consumerId] = bucket;\n\t}\n\treturn {\n\t\tbyConsumer,\n\t\twildcard\n\t};\n}\nasync function loadCredentialAssignments(options) {\n\tif (!isDatabaseInitialized()) return EMPTY_ASSIGNMENT_SET;\n\treturn buildAssignmentSet(await listCredentialAssignmentsByTarget$1(options));\n}\nasync function withCredentialAssignments(context, options) {\n\tconst assignments = await loadCredentialAssignments(options);\n\treturn {\n\t\t...context,\n\t\tassignments\n\t};\n}\n//#endregion\n//#region src/resolve-keystroke-instance.ts\nfunction pickKeystrokeInstanceRow(rows, key, consumer) {\n\tif (rows.length === 0) return;\n\tif (rows.length === 1) return rows[0];\n\tconst defaults = rows.filter((row) => row.isDefault);\n\tif (defaults.length === 1) return defaults[0];\n\tif (consumer !== void 0) throw new NeedsSelectionError({\n\t\tkey,\n\t\toptions: rows.map((row) => ({\n\t\t\tid: row.id,\n\t\t\tlabel: row.name ?? row.label,\n\t\t\tscopeType: row.scopeType,\n\t\t\tscopeId: row.scopeId\n\t\t})),\n\t\tconsumer\n\t});\n\treturn rows.find((row) => row.isDefault) ?? rows[0];\n}\nasync function resolveAssignedKeystrokeInstance(app, assignments, consumerId) {\n\tconst assignedId = selectAssignedInstanceId(assignments, consumerId, app);\n\tif (!assignedId) return;\n\tconst row = await selectCredentialInstanceById$2(assignedId);\n\tif (!row || row.authKind !== \"keystroke\" || !row.connectionId || row.appSlug !== app) return;\n\treturn {\n\t\tinstanceId: assignedId,\n\t\tscopeType: row.scopeType,\n\t\tscopeId: row.scopeId\n\t};\n}\n/** Assignment lookup (when assignments provided) then ordered scope walk. User scope only when included in scopes. */\nasync function resolveKeystrokeInstanceId(options) {\n\tconst assignments = options.assignments ?? (options.assignmentTarget ? await loadCredentialAssignments({\n\t\ttargetType: options.assignmentTarget.type,\n\t\ttargetKey: options.assignmentTarget.key\n\t}) : void 0);\n\tif (assignments) {\n\t\tconst assigned = await resolveAssignedKeystrokeInstance(options.app, assignments, options.consumerId);\n\t\tif (assigned) return assigned;\n\t}\n\tfor (const [scopeType, scopeId] of options.scopes) {\n\t\tconst row = pickKeystrokeInstanceRow((await selectCredentialInstancesForScope$2(options.app, scopeType, scopeId)).filter((row) => row.authKind === \"keystroke\" && row.connectionId), options.app, options.consumer);\n\t\tif (row) return {\n\t\t\tinstanceId: row.id,\n\t\t\tscopeType: row.scopeType,\n\t\t\tscopeId: row.scopeId\n\t\t};\n\t}\n}\n//#endregion\n//#region src/describe-credential-binding.ts\nfunction toSummary(row) {\n\treturn {\n\t\tid: row.id,\n\t\tappSlug: row.appSlug,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tscopeType: row.scopeType,\n\t\tscopeId: row.scopeId,\n\t\tisDefault: row.isDefault\n\t};\n}\n/** Pick the single instance for a scope: the only one, or the unique default; else ambiguous. */\nfunction pickInstance$1(rows) {\n\tif (rows.length === 0) return { kind: \"none\" };\n\tif (rows.length === 1) return {\n\t\tkind: \"row\",\n\t\trow: rows[0]\n\t};\n\tconst defaults = rows.filter((row) => row.isDefault);\n\tif (defaults.length === 1) return {\n\t\tkind: \"row\",\n\t\trow: defaults[0]\n\t};\n\treturn { kind: \"needs-selection\" };\n}\nfunction scopeIdFor(scope, context, orgId) {\n\tswitch (scope) {\n\t\tcase \"organization\": return orgId;\n\t\tcase \"project\": return context.projectId;\n\t\tcase \"user\": return context.userId;\n\t}\n}\nasync function describeCredentialBinding(options) {\n\tconst { key, scope, consumerId, context } = options;\n\tconst orgId = context.orgId ?? getServerTenantScopeId();\n\tconst assignedId = selectAssignedInstanceId(context.assignments, consumerId, key);\n\tif (assignedId) {\n\t\tconst row = await selectCredentialInstanceById$2(assignedId);\n\t\tif (row && row.appSlug === key) return {\n\t\t\tpolicy: \"assigned\",\n\t\t\trow: toSummary(row)\n\t\t};\n\t}\n\tif (scope) {\n\t\tconst scopeId = scopeIdFor(scope, context, orgId);\n\t\tconst picked = scopeId ? pickInstance$1(await selectCredentialInstancesForScope$2(key, scope, scopeId)) : { kind: \"none\" };\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"scope-pinned\",\n\t\t\tpinnedScope: scope,\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\treturn {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: picked.kind === \"needs-selection\" ? \"needs-selection\" : \"missing\",\n\t\t\tpinnedScope: scope\n\t\t};\n\t}\n\tif (context.projectId) {\n\t\tconst picked = pickInstance$1(await selectCredentialInstancesForScope$2(key, \"project\", context.projectId));\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"project-default\",\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\tif (picked.kind === \"needs-selection\") return {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: \"needs-selection\"\n\t\t};\n\t}\n\tif (orgId) {\n\t\tconst picked = pickInstance$1(await selectCredentialInstancesForScope$2(key, \"organization\", orgId));\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"org-default\",\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\tif (picked.kind === \"needs-selection\") return {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: \"needs-selection\"\n\t\t};\n\t}\n\treturn {\n\t\tpolicy: \"unresolved\",\n\t\treason: \"missing\"\n\t};\n}\n//#endregion\n//#region src/parse-credential-ref.ts\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst SCOPE_PREFIXES = {\n\torg: \"organization\",\n\torganization: \"organization\",\n\tproject: \"project\",\n\tuser: \"user\"\n};\nfunction credentialScopePrefix(scopeType) {\n\tswitch (scopeType) {\n\t\tcase \"organization\": return \"org\";\n\t\tcase \"project\": return \"project\";\n\t\tcase \"user\": return \"user\";\n\t}\n}\nfunction formatCredentialRef(row) {\n\treturn `${credentialScopePrefix(row.scopeType)}/${row.slug}`;\n}\nfunction formatCredentialRefSuggestion(row) {\n\treturn `${formatCredentialRef(row)} (${row.appSlug})`;\n}\nfunction parseCredentialRef(ref) {\n\tconst trimmed = ref.trim();\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"uuid\",\n\t\tid: trimmed\n\t};\n\tconst parts = trimmed.split(\"/\").filter(Boolean);\n\tif (parts.length === 2) {\n\t\tconst scopeType = SCOPE_PREFIXES[parts[0].toLowerCase()];\n\t\tif (scopeType) return {\n\t\t\tkind: \"scope\",\n\t\t\tscopeType,\n\t\t\tslug: parts[1]\n\t\t};\n\t\treturn {\n\t\t\tkind: \"app\",\n\t\t\tappSlug: parts[0],\n\t\t\tslug: parts[1]\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"bare\",\n\t\tslug: trimmed\n\t};\n}\nfunction matchesCredentialRef(row, parsed) {\n\tswitch (parsed.kind) {\n\t\tcase \"uuid\": return row.id === parsed.id;\n\t\tcase \"scope\": return row.scopeType === parsed.scopeType && row.slug === parsed.slug;\n\t\tcase \"app\": return row.appSlug === parsed.appSlug && row.slug === parsed.slug;\n\t\tcase \"bare\": return row.slug === parsed.slug;\n\t}\n}\n//#endregion\n//#region src/resolve-credential-ref.ts\nfunction defaultCanAccess(_row) {\n\treturn true;\n}\n/** Resolve a friendly credential ref (uuid, bare slug, scope/slug, or app/slug). */\nasync function resolveCredentialRef(options) {\n\tconst parsed = parseCredentialRef(options.ref);\n\tconst canAccess = options.canAccess ?? defaultCanAccess;\n\tif (parsed.kind === \"uuid\") {\n\t\tconst row = await selectCredentialInstanceById$2(parsed.id);\n\t\tif (!row) return {\n\t\t\terror: \"Credential instance not found\",\n\t\t\tstatus: 404\n\t\t};\n\t\tif (!canAccess(row)) return {\n\t\t\terror: \"Forbidden\",\n\t\t\tstatus: 403\n\t\t};\n\t\treturn { row };\n\t}\n\tconst candidates = (await listCredentialInstancesForAssignment({ userId: options.userId })).filter((row) => canAccess(row) && matchesCredentialRef(row, parsed));\n\tif (candidates.length === 1) return { row: candidates[0] };\n\tif (candidates.length === 0) return {\n\t\terror: \"Credential instance not found\",\n\t\tstatus: 404\n\t};\n\tconst suggestions = candidates.map((row) => formatCredentialRefSuggestion(row)).join(\", \");\n\treturn {\n\t\terror: `Ambiguous credential \"${options.ref}\". Multiple instances match: ${suggestions}`,\n\t\tstatus: 400\n\t};\n}\nfunction canAssignCredentialInstance(row, userId, projectId) {\n\tswitch (row.scopeType) {\n\t\tcase \"user\": return userId !== void 0 && row.scopeId === userId;\n\t\tcase \"project\": return row.scopeId === projectId;\n\t\tcase \"organization\": return true;\n\t}\n}\nfunction canManageCredentialInstance(row, userId) {\n\tif (row.scopeType === \"user\") return userId !== void 0 && row.scopeId === userId;\n\treturn true;\n}\n//#endregion\n//#region src/context.ts\nfunction buildCredentialRunContext(input) {\n\tconst subscription = input.subscription;\n\tconst request = input.request ?? {};\n\treturn {\n\t\torgId: request.orgId ?? subscription?.orgId,\n\t\tprojectId: request.projectId ?? subscription?.projectId,\n\t\tuserId: request.userId ?? subscription?.userId,\n\t\tselection: {\n\t\t\t...subscription?.credentialSelection,\n\t\t\t...request.selection\n\t\t}\n\t};\n}\n//#endregion\n//#region src/workflow-context.ts\nfunction buildWorkflowRunContext(input) {\n\tconst request = input.request ?? {};\n\tconst userId = request.userId ?? input.subscription?.userId ?? input.actor?.userId;\n\treturn {\n\t\torgId: request.orgId,\n\t\tprojectId: request.projectId,\n\t\tuserId,\n\t\tuserIds: request.userIds,\n\t\tselection: request.selection ?? {}\n\t};\n}\n//#endregion\n//#region src/project-credential-backend.ts\nlet projectCredentialBackend;\n/** Set during server bootstrap so credential resolution reuses the plugin token-refresh registry. */\nfunction setProjectCredentialBackend(backend) {\n\tprojectCredentialBackend = backend;\n}\nfunction getProjectCredentialBackend() {\n\treturn projectCredentialBackend;\n}\n//#endregion\n//#region src/resolve-vault.ts\nfunction toSelectionOption(row) {\n\treturn {\n\t\tid: row.id,\n\t\tlabel: row.name ?? row.label,\n\t\tscopeType: row.scopeType,\n\t\tscopeId: row.scopeId\n\t};\n}\nfunction resolveUserId(key, context) {\n\treturn context.userIds?.[key] ?? context.userId;\n}\nfunction pickInstance(rows, key, consumer) {\n\tif (rows.length === 0) throw new MissingCredentialsError({\n\t\tkey,\n\t\tchainAttempted: [],\n\t\tconsumer\n\t});\n\tif (rows.length === 1) return rows[0];\n\tconst defaults = rows.filter((row) => row.isDefault);\n\tif (defaults.length === 1) return defaults[0];\n\tthrow new NeedsSelectionError({\n\t\tkey,\n\t\toptions: rows.map(toSelectionOption),\n\t\tconsumer\n\t});\n}\n/** Throttle window for last-used writes so bursty runs don't hammer the same row. */\nconst LAST_USED_THROTTLE_MS = 6e4;\n/**\n* Record that a credential was just resolved. Throttled (skip when touched within\n* {@link LAST_USED_THROTTLE_MS}) and best-effort: a write failure must never break resolution.\n*/\nasync function touchLastUsed(row) {\n\tconst last = row.lastUsedAt?.getTime();\n\tif (last !== void 0 && Date.now() - last < LAST_USED_THROTTLE_MS) return;\n\ttry {\n\t\tawait touchCredentialInstanceLastUsed$1(row.id);\n\t} catch {}\n}\nasync function resolveInstanceValue(row, requirement, backend) {\n\tconst value = await materializeInstanceValue(row, requirement, backend);\n\tawait touchLastUsed(row);\n\treturn value;\n}\nasync function materializeInstanceValue(row, requirement, backend) {\n\tif (row.authKind === \"keystroke\") {\n\t\tif (!row.connectionId) throw new MissingCredentialsError({\n\t\t\tkey: row.appSlug,\n\t\t\tchainAttempted: [\"keystroke\"]\n\t\t});\n\t\tconst scopeId = row.scopeType === \"organization\" ? getServerTenantScopeId() : row.scopeId ?? \"\";\n\t\tif (!scopeId) throw new MissingCredentialsError({\n\t\t\tkey: row.appSlug,\n\t\t\tchainAttempted: [\"keystroke\"]\n\t\t});\n\t\tconst value = {\n\t\t\tconnectionId: row.connectionId,\n\t\t\tentityId: row.sharedConnectionId ?? mcpEntityId(row.scopeType, scopeId),\n\t\t\tinstanceId: row.id\n\t\t};\n\t\treturn requirement.schema.parse(value);\n\t}\n\tif (row.authKind === \"oauth_managed\") {\n\t\tif (!row.connectionId) throw new MissingCredentialsError({\n\t\t\tkey: row.appSlug,\n\t\t\tchainAttempted: [\"oauth_managed\"]\n\t\t});\n\t\tconst token = await backend.getOAuthAccessToken(row.connectionId);\n\t\tconst tokenField = requirement.tokenField ?? \"accessToken\";\n\t\tconst value = tokenField === \"accessToken\" ? token : { [tokenField]: token.accessToken };\n\t\treturn requirement.schema.parse(value);\n\t}\n\treturn backend.resolveApiKey(row.id, requirement.schema);\n}\nasync function resolveSelectedInstance(key, instanceId, context, consumer) {\n\tconst row = await selectCredentialInstanceById$1(instanceId);\n\tif (!row || row.appSlug !== key) throw new MissingCredentialsError({\n\t\tkey,\n\t\tchainAttempted: [\"selection\"],\n\t\tconsumer\n\t});\n\tif (!credentialScopeMatchesContext(row.scopeType, row.scopeId, context)) throw new CredentialAccessDeniedError(instanceId);\n\treturn row;\n}\nfunction withTenantScope(context) {\n\treturn context.orgId ? context : {\n\t\t...context,\n\t\torgId: getServerTenantScopeId()\n\t};\n}\nfunction scopeIdForScope(scope, key, context) {\n\tswitch (scope) {\n\t\tcase \"organization\": return context.orgId;\n\t\tcase \"project\": return context.projectId;\n\t\tcase \"user\": return resolveUserId(key, context);\n\t}\n}\nasync function resolveAtScope(key, scopeType, scopeId, consumer) {\n\tconst rows = await selectCredentialInstancesForScope$1(key, scopeType, scopeId);\n\tif (rows.length === 0) return;\n\treturn pickInstance(rows, key, consumer);\n}\nasync function resolveBoundInstance(instanceId, requirement, context, consumer, backend) {\n\tconst row = await selectCredentialInstanceById$1(instanceId);\n\tif (!row || row.appSlug !== requirement.key) throw new MissingCredentialsError({\n\t\tkey: requirement.key,\n\t\tchainAttempted: [\"binding\"],\n\t\tconsumer\n\t});\n\tif (!bindingTenantReachable(row, context)) throw new CredentialAccessDeniedError(instanceId);\n\treturn resolveInstanceValue(row, requirement, backend ?? createCredentialBackend());\n}\nfunction bindingTenantReachable(row, context) {\n\tswitch (row.scopeType) {\n\t\tcase \"organization\": return row.scopeId === context.orgId;\n\t\tcase \"project\": return row.scopeId === context.projectId;\n\t\tcase \"user\": return Boolean(row.scopeId);\n\t\tdefault: return false;\n\t}\n}\n/**\n* Resolution order:\n*   1. Platform assignment (consumer-specific, then wildcard).\n*   2. Client selection in `context.selection`.\n*   3. Scope pinned on the requirement (`.scope(\"user\")`).\n*   4. Project default, then org default.\n*/\nasync function resolvePolicy(requirement, context, consumer, backend) {\n\tconst attempted = [];\n\tconst materialBackend = backend ?? createCredentialBackend();\n\tconst scoped = withTenantScope(context);\n\tconst boundId = requirement.kind !== \"keystroke\" ? selectAssignedInstanceId(scoped.assignments, consumer?.id, requirement.key) : void 0;\n\tif (boundId) return resolveBoundInstance(boundId, requirement, scoped, consumer, materialBackend);\n\tif (requirement.kind === \"keystroke\") {\n\t\tconst bound = await resolveKeystrokeInstanceId({\n\t\t\tapp: requirement.key,\n\t\t\tscopes: [],\n\t\t\tassignments: scoped.assignments,\n\t\t\tconsumerId: consumer?.id\n\t\t});\n\t\tif (bound) {\n\t\t\tconst row = await selectCredentialInstanceById$1(bound.instanceId);\n\t\t\tif (!row) throw new MissingCredentialsError({\n\t\t\t\tkey: requirement.key,\n\t\t\t\tchainAttempted: [\"binding\"],\n\t\t\t\tconsumer\n\t\t\t});\n\t\t\treturn resolveInstanceValue(row, requirement, materialBackend);\n\t\t}\n\t}\n\tconst selectionId = context.selection?.[requirement.key];\n\tif (selectionId) return resolveInstanceValue(await resolveSelectedInstance(requirement.key, selectionId, scoped, consumer), requirement, materialBackend);\n\tif (requirement.scope) {\n\t\tconst scopeId = scopeIdForScope(requirement.scope, requirement.key, scoped);\n\t\tif (scopeId) {\n\t\t\tattempted.push(requirement.scope);\n\t\t\tconst row = await resolveAtScope(requirement.key, requirement.scope, scopeId, consumer);\n\t\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend);\n\t\t}\n\t\tthrow new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: attempted.length > 0 ? attempted : [requirement.scope],\n\t\t\tconsumer\n\t\t});\n\t}\n\tif (requirement.kind === \"keystroke\") {\n\t\tconst scopes = [];\n\t\tif (scoped.projectId) {\n\t\t\tattempted.push(\"project\");\n\t\t\tscopes.push([\"project\", scoped.projectId]);\n\t\t}\n\t\tif (scoped.orgId) {\n\t\t\tattempted.push(\"organization\");\n\t\t\tscopes.push([\"organization\", scoped.orgId]);\n\t\t}\n\t\tconst resolved = await resolveKeystrokeInstanceId({\n\t\t\tapp: requirement.key,\n\t\t\tscopes,\n\t\t\tconsumerId: consumer?.id,\n\t\t\tconsumer\n\t\t});\n\t\tif (resolved) {\n\t\t\tconst row = await selectCredentialInstanceById$1(resolved.instanceId);\n\t\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend);\n\t\t}\n\t\tthrow new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: attempted,\n\t\t\tconsumer\n\t\t});\n\t}\n\tif (scoped.projectId) {\n\t\tattempted.push(\"project\");\n\t\tconst row = await resolveAtScope(requirement.key, \"project\", scoped.projectId, consumer);\n\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend);\n\t}\n\tif (scoped.orgId) {\n\t\tattempted.push(\"organization\");\n\t\tconst row = await resolveAtScope(requirement.key, \"organization\", scoped.orgId, consumer);\n\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend);\n\t}\n\tthrow new MissingCredentialsError({\n\t\tkey: requirement.key,\n\t\tchainAttempted: attempted,\n\t\tconsumer\n\t});\n}\nasync function resolveCredentialRequirements(options) {\n\tconst resolved = {};\n\tconst requirements = normalizeCredentialList(options.requirements);\n\tconst backend = options.credentialBackend ?? createCredentialBackend();\n\tfor (const requirement of requirements) resolved[requirement.key] = await resolvePolicy(requirement, options.context, options.consumer, backend);\n\treturn resolved;\n}\n//#endregion\n//#region src/create-credential-resolver.ts\nfunction createCredentialResolver(options) {\n\tconst credentialBackend = options.credentialBackend ?? getProjectCredentialBackend() ?? createCredentialBackend();\n\treturn { async resolve(requirements, consumer, contextOverride) {\n\t\treturn resolveCredentialRequirements({\n\t\t\trequirements,\n\t\t\tconsumer,\n\t\t\tcredentialBackend,\n\t\t\tcontext: {\n\t\t\t\t...options.context,\n\t\t\t\t...contextOverride,\n\t\t\t\tselection: {\n\t\t\t\t\t...options.context.selection,\n\t\t\t\t\t...contextOverride?.selection\n\t\t\t\t},\n\t\t\t\tuserIds: {\n\t\t\t\t\t...options.context.userIds,\n\t\t\t\t\t...contextOverride?.userIds\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} };\n}\n//#endregion\n//#region src/mcp/resolve-mcp-tools.ts\nasync function resolveMcpAuth(def, resolver) {\n\tif (!def.credentials?.length) return;\n\tconst credentials = await resolver.resolve(def.credentials, {\n\t\tkind: \"tool\",\n\t\tname: def.key\n\t});\n\treturn def.auth(credentials);\n}\nasync function resolveMcpTools(def, resolver) {\n\tif (!def.declaredTools?.length) {\n\t\tconst connection = await connectMcpDefinition(def, await resolveMcpAuth(def, resolver));\n\t\treturn {\n\t\t\ttoolSet: connection.toolSet,\n\t\t\tclose: connection.close\n\t\t};\n\t}\n\tlet connectionPromise;\n\tconst ensureConnected = () => {\n\t\tconnectionPromise ??= (async () => connectMcpDefinition(def, await resolveMcpAuth(def, resolver)))();\n\t\treturn connectionPromise;\n\t};\n\tconst toolSet = {};\n\tfor (const declared of def.declaredTools) {\n\t\tconst toolName = createToolName(def.key, declared.name);\n\t\ttoolSet[toolName] = tool({\n\t\t\tdescription: declared.description ?? declared.title ?? declared.name,\n\t\t\tinputSchema: jsonSchema(normalizeInputSchema({\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {},\n\t\t\t\t...declared.inputSchema\n\t\t\t})),\n\t\t\texecute: async (input, options) => {\n\t\t\t\tconst nativeTool = (await ensureConnected()).toolSet[toolName];\n\t\t\t\tif (!nativeTool?.execute) throw new Error(`MCP tool \"${declared.name}\" not found on server \"${def.key}\".`);\n\t\t\t\treturn nativeTool.execute(input, options);\n\t\t\t},\n\t\t\ttoModelOutput: async (options) => {\n\t\t\t\tconst nativeTool = (await ensureConnected()).toolSet[toolName];\n\t\t\t\tif (nativeTool?.toModelOutput) return nativeTool.toModelOutput(options);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"json\",\n\t\t\t\t\tvalue: options.output\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\treturn {\n\t\ttoolSet,\n\t\tclose: async () => {\n\t\t\tif (connectionPromise) await (await connectionPromise).close();\n\t\t}\n\t};\n}\n//#endregion\n//#region src/mcp-provider.ts\nfunction encodeOAuthState(payload) {\n\treturn encryptCredentialPayload(JSON.stringify(payload));\n}\nfunction decodeOAuthState(state) {\n\treturn JSON.parse(decryptCredentialPayload(state));\n}\nfunction oauthAppMetadata(oauth, mcpUrl, options) {\n\treturn {\n\t\tmcpUrl,\n\t\tauthorizationEndpoint: oauth.authorizationEndpoint,\n\t\ttokenEndpoint: oauth.tokenEndpoint,\n\t\tregistrationEndpoint: oauth.registrationEndpoint,\n\t\tresource: oauth.resource,\n\t\tissuer: oauth.issuer,\n\t\tscopes: oauth.scopes,\n\t\t...options?.tokenEndpointAuthMethod ? { tokenEndpointAuthMethod: options.tokenEndpointAuthMethod } : {}\n\t};\n}\nfunction oauthClientSecretForStorage(clientSecret) {\n\treturn clientSecret?.trim() ? clientSecret : \"\";\n}\nfunction grantedScopesFromToken(scope, fallbackScopes) {\n\tconst trimmed = scope?.trim();\n\tif (!trimmed) return fallbackScopes;\n\treturn trimmed.split(/\\s+/).filter(Boolean);\n}\nfunction accessTokenExpiresAt(expiresIn) {\n\tif (!expiresIn || expiresIn <= 0) return;\n\treturn new Date(Date.now() + expiresIn * 1e3);\n}\nasync function discoverMcpApp(url) {\n\tconst probe = await probeMcpAuth(url);\n\tconst template = mcpProbeToAppTemplate(probe);\n\tconst serverInfo = await probeMcpServerInfo(url);\n\tconst serverName = probe.oauth?.resourceName?.trim() || serverInfo?.title?.trim() || serverInfo?.name?.trim() || void 0;\n\tconst serverDescription = serverInfo?.description?.trim() || void 0;\n\treturn {\n\t\tdetected: probe.mode === \"oauth\" ? Boolean(probe.oauth) : probe.unauthenticatedStatus !== void 0,\n\t\ttemplate: {\n\t\t\t...template,\n\t\t\t...serverName ? { serverName } : {},\n\t\t\t...serverDescription ? { serverDescription } : {}\n\t\t}\n\t};\n}\nasync function beginMcpOAuthConnect(options) {\n\tconst appUrl = options.app.url?.trim();\n\tif (!appUrl || options.app.source !== \"mcp\" || options.app.authKind !== \"oauth\") throw new Error(\"App is not a direct MCP OAuth app\");\n\tconst discovered = await discoverOAuthServerInfo(new URL(appUrl), {});\n\tconst metadata = discovered.authorizationServerMetadata;\n\tif (!metadata?.authorization_endpoint || !metadata.token_endpoint) throw new Error(\"MCP server does not expose OAuth authorization metadata\");\n\tconst oauth = {\n\t\tissuer: metadata.issuer,\n\t\tauthorizationEndpoint: metadata.authorization_endpoint,\n\t\ttokenEndpoint: metadata.token_endpoint,\n\t\tregistrationEndpoint: metadata.registration_endpoint,\n\t\tscopes: mergeOAuthScopes(metadata.scopes_supported, discovered.resourceMetadata?.scopes_supported, options.app.oauthScopes.map((scope) => scope.name)),\n\t\tresource: discovered.resourceMetadata?.resource,\n\t\tresourceName: discovered.resourceMetadata?.resource_name?.trim() || void 0\n\t};\n\tconst defaultScopeNames = options.app.oauthScopes.flatMap((entry) => entry.defaultSelected !== false ? [entry.name] : []);\n\tconst scope = options.input.scopes?.join(\" \") || (defaultScopeNames.length > 0 ? defaultScopeNames.join(\" \") : oauth.scopes.join(\" \"));\n\tconst clientInformation = await registerClient(discovered.authorizationServerUrl, {\n\t\tmetadata,\n\t\tclientMetadata: {\n\t\t\tclient_name: \"Keystroke\",\n\t\t\tredirect_uris: [options.redirectUri],\n\t\t\tgrant_types: [\"authorization_code\", \"refresh_token\"],\n\t\t\tresponse_types: [\"code\"],\n\t\t\ttoken_endpoint_auth_method: \"client_secret_post\"\n\t\t},\n\t\tscope: scope || void 0\n\t});\n\tawait ensureOAuthApp({\n\t\tslug: options.app.slug,\n\t\tprovider: \"mcp\",\n\t\ttokenStrategy: \"refresh\",\n\t\tclientId: clientInformation.client_id,\n\t\tclientSecret: oauthClientSecretForStorage(clientInformation.client_secret),\n\t\tmetadata: oauthAppMetadata(oauth, appUrl, { tokenEndpointAuthMethod: clientInformation.token_endpoint_auth_method })\n\t});\n\tconst resourceUrl = oauth.resource ? new URL(oauth.resource) : new URL(appUrl);\n\tconst statePayload = {\n\t\tcodeVerifier: \"\",\n\t\tappSlug: options.app.slug,\n\t\torganizationId: options.organizationId,\n\t\tuserId: options.userId,\n\t\tscopeTargets: {\n\t\t\t...options.scopeTargets,\n\t\t\tprojectNamesById: options.projectNamesById\n\t\t},\n\t\tauthorizationServerUrl: discovered.authorizationServerUrl,\n\t\tresource: oauth.resource,\n\t\toauthMetadata: oauth,\n\t\tmcpUrl: appUrl,\n\t\tredirectUri: options.redirectUri,\n\t\tclientId: clientInformation.client_id,\n\t\tclientSecret: clientInformation.client_secret,\n\t\ttokenEndpointAuthMethod: clientInformation.token_endpoint_auth_method,\n\t\tlabel: options.input.label,\n\t\tcredentialInstanceId: options.input.credentialInstanceId\n\t};\n\tconst { authorizationUrl, codeVerifier } = await startAuthorization(discovered.authorizationServerUrl, {\n\t\tmetadata,\n\t\tclientInformation,\n\t\tredirectUrl: options.redirectUri,\n\t\tscope: scope || void 0,\n\t\tresource: resourceUrl\n\t});\n\tstatePayload.codeVerifier = codeVerifier;\n\tconst state = encodeOAuthState(statePayload);\n\tauthorizationUrl.searchParams.set(\"state\", state);\n\treturn { authorizeUrl: authorizationUrl.toString() };\n}\nasync function completeMcpOAuthConnect(options) {\n\tconst payload = decodeOAuthState(options.state);\n\tconst metadata = {\n\t\tissuer: payload.oauthMetadata.issuer ?? payload.authorizationServerUrl,\n\t\tauthorization_endpoint: payload.oauthMetadata.authorizationEndpoint,\n\t\ttoken_endpoint: payload.oauthMetadata.tokenEndpoint,\n\t\tregistration_endpoint: payload.oauthMetadata.registrationEndpoint,\n\t\tscopes_supported: payload.oauthMetadata.scopes,\n\t\tresponse_types_supported: [\"code\"],\n\t\tcode_challenge_methods_supported: [\"S256\"]\n\t};\n\tconst resourceUrl = payload.resource ? new URL(payload.resource) : void 0;\n\tconst tokens = await exchangeAuthorization(payload.authorizationServerUrl, {\n\t\tmetadata,\n\t\tclientInformation: {\n\t\t\tclient_id: payload.clientId,\n\t\t\t...payload.clientSecret ? { client_secret: payload.clientSecret } : {},\n\t\t\t...payload.tokenEndpointAuthMethod ? { token_endpoint_auth_method: payload.tokenEndpointAuthMethod } : {}\n\t\t},\n\t\tauthorizationCode: options.code,\n\t\tcodeVerifier: payload.codeVerifier,\n\t\tredirectUri: payload.redirectUri,\n\t\tresource: resourceUrl\n\t});\n\tconst { id: oauthAppId } = await ensureOAuthApp({\n\t\tslug: payload.appSlug,\n\t\tprovider: \"mcp\",\n\t\ttokenStrategy: \"refresh\",\n\t\tclientId: payload.clientId,\n\t\tclientSecret: oauthClientSecretForStorage(payload.clientSecret),\n\t\tmetadata: oauthAppMetadata(payload.oauthMetadata, payload.mcpUrl, { tokenEndpointAuthMethod: payload.tokenEndpointAuthMethod })\n\t});\n\tconst connectionId = await saveOAuthConnection({\n\t\tappId: oauthAppId,\n\t\texternalId: payload.userId,\n\t\taccessToken: tokens.access_token,\n\t\trefreshToken: tokens.refresh_token,\n\t\taccessTokenExpiresAt: accessTokenExpiresAt(tokens.expires_in),\n\t\tgrantedScopes: grantedScopesFromToken(tokens.scope, payload.oauthMetadata.scopes),\n\t\tmetadata: { mcpUrl: payload.oauthMetadata.resource }\n\t});\n\tawait ensureOAuthCredentialInstance({\n\t\tcredentialKey: payload.appSlug,\n\t\tconnectionId,\n\t\taccountLabel: payload.label,\n\t\texternalId: payload.userId,\n\t\tuserLabel: payload.label,\n\t\ttargets: payload.scopeTargets,\n\t\tcredentialInstanceId: payload.credentialInstanceId\n\t});\n\treturn {\n\t\tappSlug: payload.appSlug,\n\t\tconnectionId,\n\t\torganizationId: payload.organizationId\n\t};\n}\n//#endregion\n//#region src/openapi-provider.ts\nconst MAX_SPEC_BYTES = 5 * 1024 * 1024;\nfunction isRecord$1(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isOpenApiSpec(value) {\n\treturn isRecord$1(value) && (typeof value.openapi === \"string\" || typeof value.swagger === \"string\");\n}\nasync function discoverOpenApiApp(url) {\n\tconst response = await fetch(url, { redirect: \"follow\" });\n\tif (!response.ok) throw new Error(`Failed to fetch OpenAPI spec (${response.status})`);\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength && Number(contentLength) > MAX_SPEC_BYTES) throw new Error(\"OpenAPI spec is too large\");\n\tconst text = await response.text();\n\tif (text.length > MAX_SPEC_BYTES) throw new Error(\"OpenAPI spec is too large\");\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(text);\n\t} catch {\n\t\tparsed = YAML.parse(text);\n\t}\n\tif (!isOpenApiSpec(parsed)) throw new Error(\"URL does not contain a valid OpenAPI or Swagger spec\");\n\treturn {\n\t\tdetected: true,\n\t\ttemplate: openApiSpecToAppTemplate(parsed, url)\n\t};\n}\n//#endregion\n//#region src/graphql-provider.ts\nconst MAX_RESPONSE_BYTES = 5 * 1024 * 1024;\nconst INTROSPECTION_QUERY = `query IntrospectionQuery {\n  __schema {\n    queryType { name description }\n    mutationType { name description }\n  }\n}`;\nconst USAGE_AUTH_PROBE_QUERY = \"query { __typename }\";\nasync function postGraphql(endpointUrl, query) {\n\tconst response = await fetch(endpointUrl, {\n\t\tmethod: \"POST\",\n\t\tredirect: \"follow\",\n\t\theaders: {\n\t\t\t\"content-type\": \"application/json\",\n\t\t\taccept: \"application/json\"\n\t\t},\n\t\tbody: JSON.stringify({ query })\n\t});\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength && Number(contentLength) > MAX_RESPONSE_BYTES) throw new Error(\"GraphQL introspection response is too large\");\n\tconst text = await response.text();\n\tif (text.length > MAX_RESPONSE_BYTES) throw new Error(\"GraphQL introspection response is too large\");\n\tlet body;\n\ttry {\n\t\tbody = JSON.parse(text);\n\t} catch {\n\t\tthrow new Error(\"GraphQL endpoint did not return JSON\");\n\t}\n\treturn {\n\t\tresponse,\n\t\tbody,\n\t\ttext\n\t};\n}\nfunction introspectionDisabled(body) {\n\tif (!isRecord(body) || !Array.isArray(body.errors)) return false;\n\treturn body.errors.some((error) => {\n\t\tif (!isRecord(error)) return false;\n\t\treturn (typeof error.message === \"string\" ? error.message.toLowerCase() : \"\").includes(\"introspection\");\n\t});\n}\nfunction parseEndpointUrl(url) {\n\tconst trimmed = url.trim();\n\tconst parsed = new URL(trimmed);\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") throw new Error(\"GraphQL endpoint must use http or https\");\n\treturn parsed;\n}\nasync function discoverGraphqlApp(url) {\n\tconst endpointUrl = parseEndpointUrl(url).toString();\n\tconst { response, body } = await postGraphql(endpointUrl, INTROSPECTION_QUERY);\n\tconst authProbe = inferGraphqlAuthFromProbe(response.status, response.headers.get(\"www-authenticate\"), body);\n\tif (!(isRecord(body) && isRecord(body.data) && isRecord(body.data.__schema))) {\n\t\tif (response.status === 401 || response.status === 403) return {\n\t\t\tdetected: true,\n\t\t\ttemplate: graphqlIntrospectionToAppTemplate({ data: {} }, endpointUrl, authProbe)\n\t\t};\n\t\tif (response.ok && introspectionDisabled(body)) throw new Error(\"Introspection is disabled on this endpoint\");\n\t\tthrow new Error(`Failed to introspect GraphQL endpoint (${response.status})`);\n\t}\n\tlet resolvedAuthProbe = authProbe;\n\tif (resolvedAuthProbe === \"none\") {\n\t\tconst usageProbe = await postGraphql(endpointUrl, USAGE_AUTH_PROBE_QUERY);\n\t\tconst usageAuth = inferGraphqlAuthFromProbe(usageProbe.response.status, usageProbe.response.headers.get(\"www-authenticate\"), usageProbe.body);\n\t\tif (usageAuth !== \"none\") resolvedAuthProbe = usageAuth;\n\t}\n\treturn {\n\t\tdetected: true,\n\t\ttemplate: graphqlIntrospectionToAppTemplate(body, endpointUrl, resolvedAuthProbe)\n\t};\n}\n//#endregion\n//#region src/define-mcp.ts\nfunction defineMcp(def) {\n\treturn defineMcp$1(def);\n}\n//#endregion\n//#region src/parse-resolved-credentials.ts\nfunction parseResolvedCredentials(requirements, credentials) {\n\tif (requirements.length === 0) return {};\n\tconst normalized = normalizeCredentialList(requirements);\n\tconst record = credentials !== null && typeof credentials === \"object\" ? credentials : void 0;\n\tconst resolved = {};\n\tfor (const requirement of normalized) {\n\t\tconst value = record?.[requirement.key];\n\t\tif (value === void 0 || value === null) throw new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: []\n\t\t});\n\t\tconst parsed = requirement.schema.safeParse(value);\n\t\tif (!parsed.success) throw new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: []\n\t\t});\n\t\tresolved[requirement.key] = parsed.data;\n\t}\n\treturn resolved;\n}\n//#endregion\n//#region src/resolve-action-credentials.ts\n/** Requirement types from contracts — not @keystrokehq/action (avoids credentials → action). */\nasync function resolveActionCredentials(requirements, options) {\n\tif (!requirements.length) return {};\n\tconst resolveCredentials = options.resolveCredentials ?? (options.context ? createCredentialResolver({\n\t\tcontext: options.context,\n\t\toauthAdapter: options.oauthAdapter\n\t}).resolve : void 0);\n\tif (!resolveCredentials) throw new MissingCredentialsError({\n\t\tkey: normalizeCredentialList(requirements)[0].key,\n\t\tchainAttempted: [],\n\t\tconsumer: options.consumer\n\t});\n\treturn parseResolvedCredentials(requirements, await resolveCredentials(requirements, options.consumer, options.contextOverride));\n}\n//#endregion\n//#region src/oauth.ts\nconst stubOAuthTokenAdapter = { async getAccessToken() {\n\tthrow new OAuthNotConfiguredError();\n} };\nfunction createOAuthTokenRefreshRegistry() {\n\tconst handlers = /* @__PURE__ */ new Map();\n\treturn {\n\t\tregister(appKey, refresher) {\n\t\t\thandlers.set(appKey, refresher);\n\t\t},\n\t\tget(appKey) {\n\t\t\treturn handlers.get(appKey);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/backend/oauth-adapter.ts\nfunction createOAuthTokenAdapterFromBackend(backend) {\n\treturn { getAccessToken(connectionId) {\n\t\treturn backend.getOAuthAccessToken(connectionId);\n\t} };\n}\n//#endregion\nexport { CREDENTIAL_SCOPE_TYPES, CredentialAccessDeniedError, MissingCredentialsError, NeedsSelectionError, OAuthNotConfiguredError, PublicHttpUrlError, beginMcpOAuthConnect, buildAssignmentSet, buildCredentialRunContext, buildWorkflowRunContext, canAssignCredentialInstance, canManageCredentialInstance, captureCredentialToolErrors, completeMcpOAuthConnect, createCredentialBackend, createCredentialResolver, createLocalCredentialBackend, createOAuthTokenAdapterFromBackend, createOAuthTokenRefreshRegistry, createPlatformCredentialBackend, credentialScopeMatchesContext, credentialScopePrefix, decodeOAuthState, defineMcp, describeCredentialBinding, discoverGraphqlApp, discoverMcpApp, discoverOpenApiApp, encodeOAuthState, enrichCredentialError, formatCredentialErrorMessage, formatCredentialRef, formatCredentialRefSuggestion, getProjectCredentialBackend, isCredentialError, isWorkerRuntime, loadCredentialAssignments, parseCredentialRef, parseResolvedCredentials, resolveActionCredentials, resolveAgentConnectContext, resolveCredentialRef, resolveCredentialRequirements, resolveKeystrokeInstanceId, resolveMcpTools, selectAssignedInstanceId, setProjectCredentialBackend, stubOAuthTokenAdapter, withCredentialAssignments };\n\n//# sourceMappingURL=index.mjs.map","import { z } from \"zod\";\nimport { executeAction, getActionCredentialRequirements, getRunSignal, getWorkflowRunHandle, normalizeCredentialList, registerWorkflowRunGetter, runWithMcpCredentialContext } from \"@keystrokehq/action\";\nimport { defineTool, requiredDisplayTextSchema } from \"@keystrokehq/shared\";\nimport { captureConsole, logSystem, withSpan } from \"@keystrokehq/tracing\";\nimport { resolveActionCredentials } from \"@keystrokehq/credentials\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/run-canceled-error.ts\nvar RunCanceledError = class extends Error {\n\tconstructor(runId) {\n\t\tsuper(runId ? `Workflow run ${runId} was canceled` : \"Workflow run was canceled\");\n\t\tthis.name = \"RunCanceledError\";\n\t}\n};\nfunction isRunCanceledError(error) {\n\treturn error instanceof RunCanceledError;\n}\n//#endregion\n//#region src/workflow-step-invocation.ts\nfunction executeWorkflowStep(state) {\n\tconst handle = getWorkflowRunHandle();\n\tif (!handle?.workflowRunner) throw new Error(`Workflow \"${state.workflow.slug}\" can only be called as a step inside a running workflow. Run it standalone with executeWorkflow(...).`);\n\treturn handle.workflowRunner(state.workflow, state.input, { callSiteId: state.callSiteId });\n}\nfunction createWorkflowStepInvocation(state) {\n\treturn {\n\t\t__site(callSiteId) {\n\t\t\treturn createWorkflowStepInvocation({\n\t\t\t\t...state,\n\t\t\t\tcallSiteId\n\t\t\t});\n\t\t},\n\t\tthen(onfulfilled, onrejected) {\n\t\t\treturn executeWorkflowStep(state).then(onfulfilled, onrejected);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/workflow-definition.ts\nconst zodSchema = z.custom((v) => v instanceof z.ZodType, \"must be a Zod schema\");\n/** Runtime validation for an unbranded workflow definition. */\nconst workflowCoreSchema = z.object({\n\tslug: z.string().trim().min(1),\n\tname: requiredDisplayTextSchema,\n\tdescription: requiredDisplayTextSchema,\n\tsubscription: z.object({ mode: z.enum([\"system\", \"subscribable\"]).optional() }).optional(),\n\tinput: zodSchema,\n\toutput: zodSchema,\n\trun: z.function()\n});\nconst WORKFLOW = Symbol.for(\"keystroke.workflow\");\n/**\n* Validates brand + shape via `workflowCoreSchema` so discovery and guards\n* reject malformed definitions.\n*/\nfunction isWorkflow(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(WORKFLOW in value) || value[WORKFLOW] !== true) return false;\n\treturn workflowCoreSchema.safeParse(value).success;\n}\n//#endregion\n//#region src/define-workflow.ts\nfunction defineWorkflow(def) {\n\tconst result = workflowCoreSchema.safeParse(def);\n\tif (!result.success) throw new Error(`Invalid workflow definition: ${formatIssues(result.error.issues)}`);\n\tconst body = def.run;\n\tconst workflow = {\n\t\t...result.data,\n\t\t[WORKFLOW]: true\n\t};\n\tworkflow.run = ((input, ctx) => {\n\t\tif (ctx !== void 0) return body(input, ctx);\n\t\treturn createWorkflowStepInvocation({\n\t\t\tworkflow,\n\t\t\tinput\n\t\t});\n\t});\n\treturn workflow;\n}\nfunction formatIssues(issues) {\n\treturn issues.map((issue) => {\n\t\treturn `${issue.path.length > 0 ? `${issue.path.join(\".\")}: ` : \"\"}${issue.message}`;\n\t}).join(\"; \");\n}\n//#endregion\n//#region src/replay/duration.ts\nconst UNIT_MS = {\n\tms: 1,\n\ts: 1e3,\n\tm: 6e4,\n\th: 36e5,\n\td: 864e5\n};\n/** Resolve a sleep duration to an absolute resume time. */\nfunction resolveResumeAt(duration, now = /* @__PURE__ */ new Date()) {\n\tif (duration instanceof Date) return duration;\n\tif (typeof duration === \"number\") return new Date(now.getTime() + Math.max(0, duration));\n\treturn new Date(now.getTime() + parseDurationToMs(duration));\n}\nfunction parseDurationToMs(value) {\n\tconst match = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/.exec(value.trim());\n\tif (!match) throw new Error(`Invalid sleep duration \"${value}\". Use a number of ms, a Date, or a string like \"5s\", \"10m\", \"1h\".`);\n\tconst amount = Number(match[1]);\n\tconst unit = match[2];\n\treturn Math.round(amount * UNIT_MS[unit]);\n}\n//#endregion\n//#region src/replay/error.ts\nfunction serializeWorkflowError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\n/** Rebuild an Error from a recorded error so replay re-raises the same failure. */\nfunction deserializeWorkflowError(data) {\n\tconst serialized = data;\n\tconst error = new Error(serialized?.message ?? \"Workflow step failed\");\n\tif (serialized?.name) error.name = serialized.name;\n\treturn error;\n}\n//#endregion\n//#region src/replay/events-consumer.ts\n/** Indexes replay events by correlationId for O(1) cache-hit checks during replay. */\nvar EventsConsumer = class {\n\tbyCorrelationId = /* @__PURE__ */ new Map();\n\tconstructor(events) {\n\t\tfor (const event of events) {\n\t\t\tif (!event.correlationId) continue;\n\t\t\tconst list = this.byCorrelationId.get(event.correlationId);\n\t\t\tif (list) list.push(event);\n\t\t\telse this.byCorrelationId.set(event.correlationId, [event]);\n\t\t}\n\t}\n\tevents(correlationId) {\n\t\treturn this.byCorrelationId.get(correlationId) ?? [];\n\t}\n\thasEventType(correlationId, type) {\n\t\treturn this.events(correlationId).some((event) => event.type === type);\n\t}\n\t/**\n\t* Cache lookup for a step. Returns the recorded output on a `step_completed`,\n\t* re-raises the recorded error on a terminal `step_failed` (so a permanently\n\t* failed step is not re-executed), and otherwise reports a miss — including\n\t* when only `step_retrying` events exist (the step re-runs on the next pass).\n\t*/\n\tgetStepResult(correlationId) {\n\t\tconst events = this.events(correlationId);\n\t\tconst failed = events.find((event) => event.type === \"step_failed\");\n\t\tif (failed) throw deserializeWorkflowError(failed.data);\n\t\tconst completed = events.find((event) => event.type === \"step_completed\");\n\t\tif (completed) return {\n\t\t\tcompleted: true,\n\t\t\tresult: completed.data\n\t\t};\n\t\treturn { completed: false };\n\t}\n\t/** Number of prior `step_retrying` events recorded for a step (= failed attempts so far). */\n\tcountRetrying(correlationId) {\n\t\treturn this.events(correlationId).filter((event) => event.type === \"step_retrying\").length;\n\t}\n\tisSleepCompleted(correlationId) {\n\t\treturn this.hasEventType(correlationId, \"sleep_completed\");\n\t}\n\t/** Returns the persisted resumeAt for a scheduled-but-not-completed sleep, if any. */\n\tgetSleepResumeAt(correlationId) {\n\t\tconst scheduled = this.events(correlationId).find((event) => event.type === \"sleep_scheduled\");\n\t\tif (!scheduled) return;\n\t\tconst data = scheduled.data;\n\t\treturn data?.resumeAt ? new Date(data.resumeAt) : void 0;\n\t}\n\tgetHookToken(correlationId) {\n\t\treturn (this.events(correlationId).find((event) => event.type === \"hook_created\")?.data)?.token;\n\t}\n\tgetHookResult(correlationId) {\n\t\tconst resumed = this.events(correlationId).find((event) => event.type === \"hook_resumed\");\n\t\tif (!resumed) return { resolved: false };\n\t\treturn {\n\t\t\tresolved: true,\n\t\t\tpayload: resumed.data?.payload\n\t\t};\n\t}\n};\n//#endregion\n//#region src/replay/suspension.ts\n/** A promise that never settles — returned by a suspending primitive so the body parks. */\nfunction createPendingPromise() {\n\treturn new Promise(() => {});\n}\n/**\n* Collects pending items requested within a single tick and resolves once, so\n* parallel suspensions (e.g. Promise.all of two sleeps) batch into one suspension.\n*/\nvar SuspensionCoordinator = class {\n\titems = /* @__PURE__ */ new Map();\n\tscheduled = false;\n\tresolve;\n\tpromise;\n\tconstructor() {\n\t\tthis.promise = new Promise((resolve) => {\n\t\t\tthis.resolve = resolve;\n\t\t});\n\t}\n\trequest(item) {\n\t\tthis.items.set(item.correlationId, item);\n\t\tif (!this.scheduled) {\n\t\t\tthis.scheduled = true;\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.resolve([...this.items.values()]);\n\t\t\t});\n\t\t}\n\t}\n\twaitForSuspension() {\n\t\treturn this.promise;\n\t}\n};\n//#endregion\n//#region src/replay/replay-context.ts\nfunction createReplayState(params) {\n\treturn {\n\t\trunId: params.runId,\n\t\tconsumer: params.consumer,\n\t\tcoordinator: params.coordinator,\n\t\teventLog: params.eventLog,\n\t\tnewEvents: [],\n\t\tnow: params.now ?? /* @__PURE__ */ new Date(),\n\t\thookBaseUrl: params.hookBaseUrl,\n\t\tsleepCounter: 0,\n\t\thookCounter: 0,\n\t\tstepOccurrences: /* @__PURE__ */ new Map()\n\t};\n}\n/**\n* Correlation-id scope for a sub-workflow body. A sub-workflow runs inline in\n* its parent's replay state, so its steps' structural `callSiteId`s (which are\n* hashed per-file and therefore collide across composed workflows) must be\n* namespaced under the parent step. We push the parent step's correlation key\n* as a path segment; keys become `<parentSegment>/<childKey>`. Held in async\n* context (not on `ReplayState`) so parallel sub-workflows (`Promise.all`) each\n* see their own scope without a shared mutable stack racing.\n*/\nconst stepScopeStorage = new AsyncLocalStorage();\n/** Run `fn` with `segment` appended to the current correlation-id scope. */\nfunction runInStepScope(segment, fn) {\n\tconst parent = stepScopeStorage.getStore() ?? [];\n\treturn stepScopeStorage.run([...parent, segment], fn);\n}\n/** Prefix the active scope onto a step key (`<scope>/<key>`, or `<key>` at top level). */\nfunction scopedKey(key) {\n\tconst scope = stepScopeStorage.getStore();\n\treturn scope && scope.length > 0 ? `${scope.join(\"/\")}/${key}` : key;\n}\n/**\n* Occurrence-independent consumer id (`step:<scopedKey>`) for credential binding,\n* so one assignment covers every execution of a step (loops included) and, unlike\n* the raw `callSiteId`, never collides with a same-positioned step in a parent or\n* sibling sub-workflow.\n*/\nfunction stepConsumerId(callSiteId) {\n\treturn `step:${scopedKey(callSiteId)}`;\n}\n/**\n* Allocate the correlation id for a step: `step:<scopedKey>#<occurrence>`. `key` is\n* the build-injected structural `callSiteId` (so the id matches the canvas graph\n* node 1:1), falling back to the action/agent slug for un-built/test runs, and is\n* prefixed by any active sub-workflow scope. The per-key `#<occurrence>` suffix\n* gives two calls to the same site (e.g. loop iterations) distinct, replay-stable\n* ids, and inserting an unrelated call never shifts the ids of later calls (unlike\n* a single global ordinal). User-authored step ids no longer exist — ids are\n* entirely internal.\n*/\nfunction nextStepCorrelationId(state, key) {\n\tconst effectiveKey = scopedKey(key);\n\tconst occurrence = state.stepOccurrences.get(effectiveKey) ?? 0;\n\tstate.stepOccurrences.set(effectiveKey, occurrence + 1);\n\treturn `step:${effectiveKey}#${occurrence}`;\n}\nfunction createSleep(state) {\n\treturn function sleep(duration, options) {\n\t\tconst correlationId = options?.__site ? nextStepCorrelationId(state, options.__site) : `sleep#${state.sleepCounter++}`;\n\t\tif (state.consumer.isSleepCompleted(correlationId)) return Promise.resolve();\n\t\tconst scheduledResumeAt = state.consumer.getSleepResumeAt(correlationId);\n\t\tconst resumeAt = scheduledResumeAt ?? resolveResumeAt(duration, state.now);\n\t\tif (scheduledResumeAt && resumeAt.getTime() <= state.now.getTime()) {\n\t\t\tstate.newEvents.push({\n\t\t\t\tid: `sleep_completed:${state.runId}:${correlationId}`,\n\t\t\t\trunId: state.runId,\n\t\t\t\ttype: \"sleep_completed\",\n\t\t\t\tcorrelationId\n\t\t\t});\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (!scheduledResumeAt) state.newEvents.push({\n\t\t\tid: `sleep_scheduled:${state.runId}:${correlationId}`,\n\t\t\trunId: state.runId,\n\t\t\ttype: \"sleep_scheduled\",\n\t\t\tcorrelationId,\n\t\t\tdata: { resumeAt: resumeAt.toISOString() }\n\t\t});\n\t\tstate.coordinator.request({\n\t\t\tkind: \"sleep\",\n\t\t\tcorrelationId,\n\t\t\tresumeAt\n\t\t});\n\t\treturn createPendingPromise();\n\t};\n}\nfunction createHook(state) {\n\treturn function hook(options) {\n\t\tconst correlationId = options?.__site ? nextStepCorrelationId(state, options.__site) : `hook#${state.hookCounter++}`;\n\t\tconst token = options?.token ?? state.consumer.getHookToken(correlationId) ?? `hook_${crypto.randomUUID()}`;\n\t\tconst resumeUrl = state.hookBaseUrl ? `${state.hookBaseUrl}/hooks/${token}/resume` : `/hooks/${token}/resume`;\n\t\tconst schema = options?.schema ? z.toJSONSchema(options.schema) : void 0;\n\t\treturn {\n\t\t\ttoken,\n\t\t\tresumeUrl,\n\t\t\tthen(onFulfilled, onRejected) {\n\t\t\t\tconst result = state.consumer.getHookResult(correlationId);\n\t\t\t\tif (result.resolved) {\n\t\t\t\t\tconst payload = options?.schema ? options.schema.parse(result.payload) : result.payload;\n\t\t\t\t\treturn Promise.resolve(payload).then(onFulfilled, onRejected);\n\t\t\t\t}\n\t\t\t\tif (!state.consumer.hasEventType(correlationId, \"hook_created\")) state.newEvents.push({\n\t\t\t\t\tid: `hook_created:${state.runId}:${correlationId}`,\n\t\t\t\t\trunId: state.runId,\n\t\t\t\t\ttype: \"hook_created\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\tdata: schema ? {\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tschema\n\t\t\t\t\t} : { token }\n\t\t\t\t});\n\t\t\t\tstate.coordinator.request({\n\t\t\t\t\tkind: \"hook\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\ttoken,\n\t\t\t\t\t...schema ? { schema } : {}\n\t\t\t\t});\n\t\t\t\treturn createPendingPromise().then(onFulfilled, onRejected);\n\t\t\t}\n\t\t};\n\t};\n}\n//#endregion\n//#region src/run-durable-step.ts\n/**\n* Shared durable-step shell: resolve a stable `correlation_id`, short-circuit\n* from the event log on a cache hit, otherwise execute and append\n* `step_completed` immediately (per-step crash durability). A thrown step\n* appends `step_retrying` (non-fatal, re-run on the next attempt) and\n* rethrows; the terminal `step_failed` is written by the job handler once the\n* queue exhausts retries.\n*/\nasync function runDurableStep(state, options) {\n\tconst { runId, consumer, eventLog } = state;\n\tgetRunSignal().throwIfAborted();\n\tconst correlationId = nextStepCorrelationId(state, options.correlationKey ?? options.key);\n\tconst cached = consumer.getStepResult(correlationId);\n\tconst metadata = {\n\t\trunId,\n\t\t[options.metadataKey]: options.key,\n\t\tcorrelationId\n\t};\n\tif (cached.completed) {\n\t\tawait withSpan({\n\t\t\tkind: options.kind,\n\t\t\tname: options.key,\n\t\t\trefId: `${runId}:${correlationId}`,\n\t\t\tmetadata: {\n\t\t\t\t...metadata,\n\t\t\t\treplayed: true\n\t\t\t}\n\t\t}, async () => {\n\t\t\tawait logSystem(\"info\", options.replayMessage, metadata);\n\t\t});\n\t\treturn options.parseCached ? options.parseCached(cached.result) : cached.result;\n\t}\n\treturn withSpan({\n\t\tkind: options.kind,\n\t\tname: options.key,\n\t\trefId: `${runId}:${correlationId}`,\n\t\tmetadata\n\t}, async () => captureConsole(async () => {\n\t\ttry {\n\t\t\tconst result = await options.execute(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_completed:${runId}:${correlationId}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_completed\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: result\n\t\t\t});\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tconst attempt = consumer.countRetrying(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_retrying:${runId}:${correlationId}:${attempt}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_retrying\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: serializeWorkflowError(error)\n\t\t\t});\n\t\t\tstate.failedCorrelationId = correlationId;\n\t\t\tthrow error;\n\t\t}\n\t}));\n}\n//#endregion\n//#region src/create-action-runner.ts\nfunction withCredentialScopeOverride(requirements, scope) {\n\tif (!requirements || !scope) return requirements;\n\treturn normalizeCredentialList(requirements).map((requirement) => ({\n\t\t...requirement,\n\t\tscope\n\t}));\n}\n/** Builds the per-run action runner; durability lives in {@link runDurableStep}. */\nfunction createActionRunner(state, options = {}) {\n\treturn (action, input, runOptions) => runDurableStep(state, {\n\t\tkind: \"action\",\n\t\tkey: action.slug,\n\t\tcorrelationKey: runOptions?.callSiteId,\n\t\tmetadataKey: \"actionKey\",\n\t\treplayMessage: \"action replayed from checkpoint\",\n\t\tparseCached: (cached) => action.output.parse(cached),\n\t\texecute: async (correlationId) => {\n\t\t\tconst requirements = withCredentialScopeOverride(getActionCredentialRequirements(action), runOptions?.credentialScope);\n\t\t\tconst consumerId = runOptions?.callSiteId ? stepConsumerId(runOptions.callSiteId) : correlationId;\n\t\t\tconst credentials = requirements?.length ? await resolveActionCredentials(requirements, {\n\t\t\t\tresolveCredentials: options.resolveCredentials,\n\t\t\t\tcontext: options.credentialContext,\n\t\t\t\toauthAdapter: options.oauthAdapter,\n\t\t\t\tconsumer: {\n\t\t\t\t\tkind: \"action\",\n\t\t\t\t\tname: action.slug,\n\t\t\t\t\tid: consumerId\n\t\t\t\t}\n\t\t\t}) : {};\n\t\t\treturn runWithMcpCredentialContext({\n\t\t\t\t...options.mcpCredentialContext,\n\t\t\t\tconsumerId\n\t\t\t}, () => executeAction(action, input, credentials));\n\t\t}\n\t});\n}\n//#endregion\n//#region src/create-agent-step-runner.ts\n/**\n* Builds the per-run agent runner: each `agent.prompt()` in a workflow body\n* becomes a durable step keyed `step:<agentKey>#<occurrence>` (same scheme as\n* actions). The actual prompt execution is delegated to `runAgent`, supplied\n* by the host (server) via `executeWorkflow({ runAgent })`.\n*/\nfunction createAgentStepRunner(state, runAgent) {\n\treturn (agent, input, options) => {\n\t\tconst slug = agent.slug;\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"agent_session\",\n\t\t\tkey: slug,\n\t\t\tcorrelationKey: options?.callSiteId,\n\t\t\tmetadataKey: \"agentKey\",\n\t\t\treplayMessage: \"agent step replayed from checkpoint\",\n\t\t\texecute: (_correlationId) => runAgent(agent, input, options?.runPrompt)\n\t\t});\n\t};\n}\n//#endregion\n//#region src/create-llm-step-runner.ts\n/**\n* Builds the per-run LLM runner: each `promptLlm()` in a workflow body becomes a\n* durable step keyed `step:promptLlm#<occurrence>`. The actual LLM call is\n* delegated to `runLlm`, supplied by the host (server) via `executeWorkflow({ runLlm })`.\n*/\nfunction createLlmStepRunner(state, runLlm) {\n\treturn (opts) => runDurableStep(state, {\n\t\tkind: \"llm\",\n\t\tkey: \"promptLlm\",\n\t\tcorrelationKey: opts.callSiteId,\n\t\tmetadataKey: \"llmKey\",\n\t\treplayMessage: \"llm step replayed from checkpoint\",\n\t\tparseCached: (cached) => opts.outputSchema ? opts.outputSchema.parse(cached) : cached,\n\t\texecute: (_correlationId) => runLlm(opts)\n\t});\n}\n//#endregion\n//#region src/create-workflow-step-runner.ts\n/**\n* Builds the per-run sub-workflow runner: each `workflow.run(input)` inside a\n* workflow body becomes a durable step keyed by its build-injected `callSiteId`\n* (`step:<callSiteId>#<occurrence>`), falling back to the slug for un-built runs.\n* The sub-workflow's body runs inline in the same replay state (its action/agent/\n* LLM steps and `ctx.sleep`/`ctx.hook` stay durable) but under a correlation-id\n* scope named after this step, so the child's steps never collide with equally\n* positioned steps in the parent. Its validated output is checkpointed so a\n* replay skips the whole sub-workflow once it completes.\n*/\nfunction createWorkflowStepRunner(state, ctx) {\n\treturn (workflowUnknown, input, options) => {\n\t\tconst workflow = workflowUnknown;\n\t\tconst parsedInput = workflow.input.parse(input);\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"workflow_run\",\n\t\t\tkey: workflow.slug,\n\t\t\tcorrelationKey: options?.callSiteId,\n\t\t\tmetadataKey: \"workflowKey\",\n\t\t\treplayMessage: \"workflow step replayed from checkpoint\",\n\t\t\tparseCached: (cached) => workflow.output.parse(cached),\n\t\t\texecute: async () => {\n\t\t\t\treturn runInStepScope(options?.callSiteId ?? workflow.slug, async () => {\n\t\t\t\t\tconst output = await workflow.run(parsedInput, ctx);\n\t\t\t\t\treturn workflow.output.parse(output);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t};\n}\n//#endregion\n//#region src/run-context.ts\nconst storage = new AsyncLocalStorage();\nregisterWorkflowRunGetter(() => {\n\tconst store = storage.getStore();\n\tif (!store) return;\n\treturn {\n\t\tactionRunner: store.actionRunner,\n\t\tagentRunner: store.agentRunner,\n\t\tllmRunner: store.llmRunner,\n\t\tworkflowRunner: store.workflowRunner\n\t};\n});\nfunction runWithWorkflowContext(store, fn) {\n\treturn storage.run(store, fn);\n}\n//#endregion\n//#region src/replay/memory-event-log.ts\n/** In-memory durable log for inline execution and tests. */\nvar MemoryEventLog = class {\n\tevents = [];\n\tids = /* @__PURE__ */ new Set();\n\tasync append(event) {\n\t\tconst id = event.id ?? crypto.randomUUID();\n\t\tif (this.ids.has(id)) return false;\n\t\tthis.ids.add(id);\n\t\tthis.events.push({\n\t\t\tid,\n\t\t\trunId: event.runId,\n\t\t\tseq: this.events.length,\n\t\t\ttype: event.type,\n\t\t\tcorrelationId: event.correlationId ?? null,\n\t\t\tdata: event.data ?? null\n\t\t});\n\t\treturn true;\n\t}\n\tasync listReplay(runId) {\n\t\treturn this.events.filter((event) => event.runId === runId).map((event) => ({ ...event }));\n\t}\n};\n//#endregion\n//#region src/execute-workflow.ts\n/**\n* The single way to run a workflow: replay its event log from the top, execute\n* un-cached primitives, and either complete/fail or suspend at the first\n* un-satisfied sleep/hook. New events (sleep_scheduled/sleep_completed/\n* hook_created/run_completed/run_failed) are flushed before returning.\n*\n* Durability comes entirely from the log — a suspended run resumes by calling\n* this again with the same `runId` and event log once the sleep is due or the\n* hook is resumed.\n*/\nasync function executeWorkflow(workflow, input, options = {}) {\n\tconst runId = options.runId ?? crypto.randomUUID();\n\tconst eventLog = options.eventLog ?? new MemoryEventLog();\n\tconst signal = getRunSignal();\n\tconst consumer = new EventsConsumer(await eventLog.listReplay(runId));\n\tconst coordinator = new SuspensionCoordinator();\n\tconst state = createReplayState({\n\t\trunId,\n\t\tconsumer,\n\t\tcoordinator,\n\t\teventLog,\n\t\thookBaseUrl: options.hookBaseUrl,\n\t\tnow: options.now\n\t});\n\tconst actionRunner = createActionRunner(state, {\n\t\tresolveCredentials: options.resolveCredentials,\n\t\tcredentialContext: options.credentialContext,\n\t\toauthAdapter: options.oauthAdapter,\n\t\tmcpCredentialContext: { assignmentTarget: {\n\t\t\ttype: \"workflow\",\n\t\t\tkey: workflow.slug\n\t\t} }\n\t});\n\tconst ctx = {\n\t\trunId,\n\t\tsleep: createSleep(state),\n\t\thook: createHook(state),\n\t\t...options.context\n\t};\n\tconst agentRunner = options.runAgent ? createAgentStepRunner(state, options.runAgent) : void 0;\n\tconst llmRunner = options.runLlm ? createLlmStepRunner(state, options.runLlm) : void 0;\n\tconst workflowRunner = createWorkflowStepRunner(state, ctx);\n\tconst validatedInput = workflow.input.parse(input);\n\tconst bodyPromise = runWithWorkflowContext({\n\t\tactionRunner,\n\t\tagentRunner,\n\t\tllmRunner,\n\t\tworkflowRunner,\n\t\trunId\n\t}, () => captureConsole(async () => workflow.run(validatedInput, ctx)));\n\tlet onAbort;\n\tconst waitForAbort = signal.aborted ? Promise.resolve({ type: \"canceled\" }) : new Promise((resolve) => {\n\t\tonAbort = () => resolve({ type: \"canceled\" });\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n\tconst outcome = await Promise.race([\n\t\tbodyPromise.then((output) => ({\n\t\t\ttype: \"done\",\n\t\t\toutput\n\t\t}), (error) => ({\n\t\t\ttype: \"error\",\n\t\t\terror\n\t\t})),\n\t\tcoordinator.waitForSuspension().then((items) => ({\n\t\t\ttype: \"suspended\",\n\t\t\titems\n\t\t})),\n\t\twaitForAbort\n\t]);\n\tif (onAbort) signal.removeEventListener(\"abort\", onAbort);\n\tlet result;\n\tif (outcome.type === \"suspended\") {\n\t\tbodyPromise.catch(() => {});\n\t\tresult = {\n\t\t\tstatus: \"suspended\",\n\t\t\titems: outcome.items\n\t\t};\n\t} else if (outcome.type === \"done\") {\n\t\tconst output = workflow.output.parse(outcome.output);\n\t\tstate.newEvents.push({\n\t\t\tid: `run_completed:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_completed\",\n\t\t\tdata: { output }\n\t\t});\n\t\tresult = {\n\t\t\tstatus: \"completed\",\n\t\t\toutput\n\t\t};\n\t} else if (outcome.type === \"canceled\" || isRunCanceledError(outcome.error)) {\n\t\tbodyPromise.catch(() => {});\n\t\tstate.newEvents.push({\n\t\t\tid: `run_canceled:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_canceled\"\n\t\t});\n\t\tresult = { status: \"canceled\" };\n\t} else result = {\n\t\tstatus: \"failed\",\n\t\terror: outcome.error,\n\t\tfailedCorrelationId: state.failedCorrelationId\n\t};\n\tfor (const event of state.newEvents) await eventLog.append(event);\n\treturn result;\n}\n//#endregion\n//#region src/prompt-llm.ts\nfunction promptLlm(prompt, opts) {\n\tconst handle = getWorkflowRunHandle();\n\tif (!handle?.llmRunner) throw new Error(\"promptLlm must run inside a workflow with an injected llm executor (executeWorkflow({ runLlm })).\");\n\tconst { __site, ...rest } = opts;\n\treturn handle.llmRunner({\n\t\tprompt,\n\t\t...rest,\n\t\t...typeof __site === \"string\" ? { callSiteId: __site } : {}\n\t});\n}\n//#endregion\n//#region src/workflow-tool.ts\nlet executor;\nfunction registerWorkflowToolExecutor(fn) {\n\tif (executor) throw new Error(\"workflow tool executor already registered\");\n\texecutor = fn;\n}\nfunction getWorkflowToolExecutor() {\n\tif (!executor) throw new Error(\"workflow tool executor not registered\");\n\treturn executor;\n}\nfunction assertWorkflowToolInput(workflow) {\n\tif (!(\"shape\" in workflow.input) || typeof workflow.input.shape !== \"object\") throw new Error(`Workflow \"${workflow.slug}\" cannot be used as an agent tool: input schema must be a Zod object.`);\n}\nfunction resolveWorkflowTool(workflow, context = {}) {\n\tassertWorkflowToolInput(workflow);\n\tconst key = workflow.slug;\n\tconst description = workflow.description;\n\treturn defineTool({\n\t\tname: key,\n\t\tlabel: key,\n\t\tdescription,\n\t\tparameters: workflow.input,\n\t\tasync execute(toolCallId, params) {\n\t\t\tconst output = await withSpan({\n\t\t\t\tkind: \"tool_call\",\n\t\t\t\tname: key,\n\t\t\t\trefId: toolCallId,\n\t\t\t\tmetadata: {\n\t\t\t\t\ttool: key,\n\t\t\t\t\ttype: \"workflow\"\n\t\t\t\t}\n\t\t\t}, () => getWorkflowToolExecutor()(workflow, params, {\n\t\t\t\tworkflowKey: key,\n\t\t\t\t...context\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(output)\n\t\t\t\t}],\n\t\t\t\tdetails: output\n\t\t\t};\n\t\t}\n\t});\n}\n//#endregion\nexport { MemoryEventLog, RunCanceledError, defineWorkflow, deserializeWorkflowError, executeWorkflow, isRunCanceledError, isWorkflow, promptLlm, registerWorkflowToolExecutor, resolveWorkflowTool, serializeWorkflowError };\n\n//# sourceMappingURL=index.mjs.map"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301],"mappings":";;;;;;;;;;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